Qt中的委托通常都是继承自QStyledItemDelegate或者QItemDelegate,二者的区别主要在于绘制方式,QStyledItemDelegate会使用当前样式绘制,并且能够使用qss,因此在在自定义委托时,一般使用 QStyledItemDelegate作为基类。除此之外,二者基本没有区别,写法和用法都一样。
继承 QStyledItemDelegate需要实现以下几个函数:
- createEditor():returns the widget used to change data from the model and can be reimplemented to customize editing behavior.
- setEditorData(): provides the widget with data to manipulate.
- updateEditorGeometry():ensures that the editor is displayed correctly with respect to the item view.
- setModelData():returns updated data to the model.
virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
virtual void setEditorData(QWidget *editor, const QModelIndex &index) const;
virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
假设一个QTableView中,某一列的数据全是“选项一,选项二,选项三”中的任意一个选项,这种情况下就可以把这一列的代理设置成以QComboBox为基础的,每次修改数据时双击表格中的cell,出现下拉框来选择数据。详细代码如下:
nari_combodelegate.h
#ifndef NARI_COMBODELEGATE_H
#define NARI_COMBODELEGATE_H
class NARI_ComboDelegate : public QItemDelegate
{
Q_OBJECT
public:
NARI_ComboDelegate(const QStringList &items, QObject *parent = NULL);
~NARI_ComboDelegate();
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) co

最低0.47元/天 解锁文章
1467





