就是显示自定义的控件

  1. _____
  2. | 数据 |
  3. -----
  4. ^
  5. |
  6. V
  7. -------
  8. | Model | <-----------
  9. ------- | 编辑
  10. | V
  11. | 显示 -----
  12. | | 代理 |
  13. | -----
  14. V ^
  15. ------ | 显示
  16. | View | <------------|
  17. ------

QAbstractItemDelegate 是所有代理类的基类。

  • QStyledItemDelegate: 是view组件使用的缺省代理类(可以使用样式表绘制组件)-推荐
  • QItemDelegate: 也是类似功能的类(不可以用样式表)。

    • QSqlRelationalDelegate:

如果是要编辑的话,以下几函数必须实现:

  • createEditor(): 创建用于编辑模型数据的widget组件, 如QSpinBox,QComboBox
  • setEditorData(): 从数据模型获取数据,供widget组件进行编辑
  • setModelData(): 将widget上的数据更新到数据模型
  • updateEditorGeometry(): 用于给widget组件设置一个合适的大小

1. 例子:

在 tableView 里,默认的双击编辑是 QLineEdit,现在改成 QSpinBox:

1. 在项目中,添加 C++ 类

  • 继承自: QStyledItemDelegate 且包含 QObject
  • 取名为: qintdelegate

    • qintdelegate.h
    • qintdelegate.cpp

2. 在引用处添加:

  • xxx.h:
  1. #include "qintdeleagte.h"
  2. private:
  3. QIntDeleagte intSpinDelegate;
  • xxx.cpp:
  1. // 为第0列添加delegate
  2. ui->tableView->setItemDelegateForColumn(0, &intSpinDelegate);

3. 实现四个重载函数:

  • qintdelegate.h:
  1. public:
  2. void setEditorData(QWidget *editor, const QModelIndex &index) const override;
  3. void setModelData(QWidget *editor,
  4. QAbstractItemModel *model,
  5. const QModelIndex &index) const override;
  6. void updateEditorGeometry(QWidget *editor,
  7. const QStyleOptionViewItem &option,
  8. const QModelIndex &index) const override;
  • qintdelegate.cpp:
  1. // 创建显示的控件
  2. QWidget *QIntDeleagte::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
  3. {
  4. Q_UNUSED(option);
  5. Q_UNUSED(index);
  6. QSpinBox *editor = new QSpinBox(parent);
  7. editor->setMinimum(0);
  8. editor->setMaximum(13);
  9. editor->setFrame(false);
  10. return editor;
  11. }
  12. // 从model中获取数据,用于编辑
  13. void QIntDeleagte::setEditorData(QWidget *editor, const QModelIndex &index) const
  14. {
  15. int value = index.model()->data(index, Qt::EditRole).toInt();
  16. QSpinBox *spinBox = static_cast<QSpinBox *>(editor);
  17. spinBox->setValue(value);
  18. }
  19. // 将控件上的数据更新到model中
  20. void QIntDeleagte::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
  21. {
  22. QSpinBox *spinBox = static_cast<QSpinBox *>(editor);
  23. spinBox->interpretText();
  24. int value = spinBox->value();
  25. model->setData(index, value, Qt::EditRole);
  26. }
  27. // 给控件设置适合的大小
  28. void QIntDeleagte::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
  29. {
  30. Q_UNUSED(index);
  31. editor->setGeometry(option.rect);
  32. }