Qt自定义委托

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
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值