主要是用QItemDelegate,写一个类继承QItemDelegate,实现createEditor(),setEditorData()和setModelData()方法
createEditor()实现当双击时,弹出的QComboBox中显示的内容
QWidget * ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QComboBox *editor = new QComboBox(parent);
for (int i = 0, size = _strList.count(); i < size; i++)
editor->addItem(_strList.at(i));
return editor;
}
setEditorData()来设置QComboBox当前editor的数据
void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString text = index.model()->data(index, Qt::EditRole).toString();
QComboBox *comboBox = static_cast<QComboBox*>(editor);
int tindex = comboBox->findText(text);
comboBox->setCurrentIndex(tindex);
}
setModelData()设置QTableView的model的数据
void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
QString text = comboBox->currentText();
model->setData(index, text, Qt::EditRole);
}
最后只需要创建ItemDelegate的对象,设置QTableView对应列的代理即可
ItemDelegate *itemDelegate = new ItemDelegate(this);
ui.tableView->setItemDelegateForColumn(1, itemDelegate);//设置第二列