1. 模型(Model)
实现自定义模型可以通过QAbstractItemModel类继承,也可以通过QAbstractListModel和QAbstractTableModel类继承实现列表模型或表格模型
2. 视图(View)
实现自定义视图可以通过QAbstractItemView类继承,对所需的纯虚函数进行重定义与实现,对于QAbstractItemView类中的纯虚函数,在子类中必须进行重定义,但不一定要实现
3. 代理(Delegate)
从QItemDelegate类继承,在表格中嵌入各种不同的控件,通过表格中的控件对编辑的内容进行限定,控件只有在需要编辑数据项时才会显示
- QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;完成创建控件的工作,并对控件的内容进行限定
QWidget* ComboBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const { QComboBox* editor = new QComboBox(parent); editor->addItem("张三"); editor->addItem("李四"); //安装事件过滤器,使ComboBoxDelegate能够捕获QComboBox对象的事件 editor->installEventFilter(const_cast<ComboBoxDelegate*>(this)); return editor; }
- void setEditorData(QWidget* editor, const QModelIndex& index) const;设置编辑控件时显示的数据,将Model中的数据更新至Delegate中,相当于一个初始化工作。例如表格中某个单元格的内容为"张三",则双击该单元格出现的ComboBox控件的显示值为"张三",即把model中的显示值初始化到控件中
void ComboBoxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { QString str = index.model()->data(index).toString(); QComboBox* comboBox = static_cast<QComboBox*>(editor); comboBox->setCurrentIndex(comboBox->findText(str)); }
- void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const;将Delegate中对数据的改变更新至Model中
void ComboBoxDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const { QComboBox* comboBox = static_cast<QComboBox*>(editor); QString str = comboBox->currentText(); model->setData(index, str); }