QtCreator委托类 QItemDelegate,自定义委托类

1 基本概念

QAbstractItemDelegate:所有委托类的基类,使用paint()和sizeHint()来使它们可以渲染自身的内容
2 自定义委托

2.1 向项目中添加新的C++类,类名SpinBoxDelegate,基类QItemDelegate,类型信息继承自QObject
      向自定义的委托类中添加管理编辑器部件的函数

    //创建编辑器
    QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) 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;
 
 
2.1.1 添加函数的实现
//创建编辑器,当视图需要一个编辑器时,它通知委托来为被修改的项目提供一个编辑器部件
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();//确保获得的是QSpinBox中最近更新的数值,标准的QItemDelegate会在完成编辑后发射closeEdit信号
    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);
}
2.2 使用自定义的委托
2.2.1 界面实现文件中添加头文件
#include "spinboxdelegate.h"
2.2.2在界面文件的cpp中构造函数里面添加如下代码:
    //设置自定义的委托
    SpinBoxDelegate* delegate = new SpinBoxDelegate(this);
    tableView->setItemDelegate(delegate);
 
  
转载自:http://m.blog.csdn.net/blog/psujtfc/37958567
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值