用户实现代理类时,可以从两个类中继承
第一种:从QAbstractItemDelegate类中继承,至少需要实现两个函数,paint()和sizeHint()
void MyDelegate::paint(QPainter*painter,const QStyleOptionViewItem&option, constQModelIndex&index)const { if (index.column() == 需代理的列) { int content = index.model()->data(index, Qt::DisplayRole).toInt(); // 取到模型中原来的内容 // ... 修改取到的值,代码略 QStyleOptionViewItem myOption = option; myOption.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; // 处理文本的对齐方式 (不重要) drawDisplay(painter, myOption, myOption.rect, 修改后的值); // 写回处理后的值 drawFocus(painter, myOption, myOption.rect); // 如果当前项具有焦点,它就绘制一个焦点矩形(不重要) } else{ QItemDelegate::paint(painter, option, index); } } QSize MyDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { if (条件) { return Qsize(int width, int height); // 用户定义 } else { return QStyledItemDelegate::sizeHint(option, index); } }
第二种:从QItemDelegate类继承,一般使用这种方式,减少代码量
.h文件
#ifndef DELEGATE_H #define DELEGATE_H #include <QItemDelegate> #include <QModelIndex> #include <QObject> #include <QSize> #include <QSpinBox> class SpinBoxDelegate : public QItemDelegate { Q_OBJECT public: SpinBoxDelegate(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; }; #endif
.cpp文件
SpinBoxDelegate::SpinBoxDelegate(QObject *parent) : QItemDelegate(parent) { } QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { QSpinBox *editor = new QSpinBox(parent); editor->setMinimum(0); editor->setMaximum(100); return editor; } void SpinBoxDelegate::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); } void SpinBoxDelegate::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 SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect); // option.rect属性中保存了条目的位置,这里将控件设置在刚好占住条目的位置 }