自定义代理类的基本设计要求:
qt中有关的代理类:
QAbstractItemDelegate是所有代理类的抽象基类;
QStyledItemDelegate是视图组件使用的缺省的代理类,QItemDelegate也是类似功能的类。
QStyledItemDelegate 与 QItemDelegate的差别在于:QStyledItemDelegate可以使用当前的样式表设置来绘制组件,建议使用QStyledItemDelegate作为自定义代理组件的基类。
QStyledItemDelegate 或者是 QItemDelegate继承设计自定义代理组件,都必须实现4个函数:
createEditor()函数:创建用于编辑模型数据的widget组件,如一个QSpinBox组件,或一个QComboBox组件;
setEditorData():函数从数据模型获取数据,供 widget组件进行编辑;
setModelData():将 widget上的数据更新到数据模型;
updateEditorGeometry():用于给widget组件设置一个合适的大小。
函数原型://自定义代理组件必须继承以下4个函数 QWidget *createEditor(QWidget *parent, const QStyleoptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const Q_DECL_OVERRIDE; void updateEditorGeometry(QWidget *editor, const QstyleoptionvViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
基于QSpinBox的自定义代理类
createEditor()函数的实现:
用于创建需要的编辑组件
QWidget *QWIntSpinDelegate::createEditor (Qwidget *parent,
const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//创建代理编辑组件
QSpinBox *editor = new QSpinBox (parent) ;
editor->setFrame (false) ; //设置为无边框
editor->setMinimum (0) ;
editor->setMaximum (10000) ;
return editor;//返回此编辑器
}
setEditorData()函数的实现:
用于从数据模型获取数值,设置编辑器的显示值。当双击一个单元格进入编辑状态时,就会自动调用此函数。
//函数传递来的参数editor 指向代理编辑组件,
//index是关联的数据单元的模型索引。
//通过强制类型转换将editor 转换为 QSpinBox类型组件 spinBox,然后将获取的数值设置为spinBox的值。
void QWIntspinDelegate::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) ;
}
setModelData()函数
setModelData()函数用于将代理编辑器上的值更新给数据模型,当用户在界面上完成编辑时会自动调用此函数,将界面上的数据更新到数据模型。
void QWIntSpinDelegate::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); }
updateEditorGeometry()函数
updateEditorGeometry()函数用于为代理组件设置一个合适的大小,函数传递的参数 option 的rect变量定义了单元格适合显示代理组件的大小,直接设置为此值即可。
void QWIntSpinDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { //设置组件大小 editor->setGeometry(option.rect) ; }