就是显示自定义的控件
_____
| 数据 |
-----
^
|
V
-------
| Model | <-----------
------- | 编辑
| V
| 显示 -----
| | 代理 |
| -----
V ^
------ | 显示
| View | <------------|
------
QAbstractItemDelegate 是所有代理类的基类。
- QStyledItemDelegate: 是view组件使用的缺省代理类(可以使用样式表绘制组件)-推荐。
QItemDelegate: 也是类似功能的类(不可以用样式表)。
- QSqlRelationalDelegate:
如果是要编辑的话,以下几函数必须实现:
createEditor()
: 创建用于编辑模型数据的widget组件, 如QSpinBox,QComboBoxsetEditorData()
: 从数据模型获取数据,供widget组件进行编辑setModelData()
: 将widget上的数据更新到数据模型updateEditorGeometry()
: 用于给widget组件设置一个合适的大小
1. 例子:
在 tableView 里,默认的双击编辑是 QLineEdit,现在改成 QSpinBox:
1. 在项目中,添加 C++ 类
- 继承自:
QStyledItemDelegate
且包含QObject
取名为: qintdelegate
- qintdelegate.h
- qintdelegate.cpp
2. 在引用处添加:
- xxx.h:
#include "qintdeleagte.h"
private:
QIntDeleagte intSpinDelegate;
- xxx.cpp:
// 为第0列添加delegate
ui->tableView->setItemDelegateForColumn(0, &intSpinDelegate);
3. 实现四个重载函数:
- qintdelegate.h:
public:
void setEditorData(QWidget *editor, const QModelIndex &index) const override;
void setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const override;
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
- qintdelegate.cpp:
// 创建显示的控件
QWidget *QIntDeleagte::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(option);
Q_UNUSED(index);
QSpinBox *editor = new QSpinBox(parent);
editor->setMinimum(0);
editor->setMaximum(13);
editor->setFrame(false);
return editor;
}
// 从model中获取数据,用于编辑
void QIntDeleagte::setEditorData(QWidget *editor, const QModelIndex &index) const
{
int value = index.model()->data(index, Qt::EditRole).toInt();
QSpinBox *spinBox = static_cast<QSpinBox *>(editor);
spinBox->setValue(value);
}
// 将控件上的数据更新到model中
void QIntDeleagte::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QSpinBox *spinBox = static_cast<QSpinBox *>(editor);
spinBox->interpretText();
int value = spinBox->value();
model->setData(index, value, Qt::EditRole);
}
// 给控件设置适合的大小
void QIntDeleagte::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(index);
editor->setGeometry(option.rect);
}