Delegate 部分 关键是重写这四个函数:
1 QWidget *createEditor (QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const ;
1 void setEditorData (QWidget *editor, const QModelIndex &index) const ;
1 void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const ;
1 void updateEditorGeometry (QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const ;
头文件 combodelegate.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class ComboDelegate :public QItemDelegate{ Q_OBJECT public : ComboDelegate(QObject *parent=0 ); QWidget *createEditor (QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const ; void setEditorData (QWidget *editor, const QModelIndex &index) const ; void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const ; void updateEditorGeometry (QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const ; };
源文件 combodelegate.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 QWidget *ComboDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QComboBox *editor=new QComboBox(parent); editor->addItem("程序员" ); editor->addItem("网管" ); editor->addItem("修电脑的" ); editor->addItem("送水的" ); editor->installEventFilter(const_cast <ComboDelegate*>(this )); return editor; } void ComboDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString str=index.model()->data(index).toString(); QComboBox *box=static_cast <QComboBox*>(editor); int i=box->findText(str); box->setCurrentIndex(i); } void ComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *box=static_cast <QComboBox*>(editor); QString str=box->currentText(); model->setData(index,str); } void ComboDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); }
Model 部分 重写 flag()
函数 和 setData()
函数
1 2 3 4 5 6 Qt::ItemFlags flags (const QModelIndex &index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); flags |= Qt::ItemIsEditable; return flags; }
1 2 3 4 5 6 7 8 9 bool setData (const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid()) return false ; if (role == Qt::EditRole) { ; } return true ; }
View 部分 手动实现重命名 1 2 3 4 void NovelDirListView::slotRenameChapter(){ edit(currentIndex()); }