自定义管理视图交互的委托

1、视图效果

2、 视图类通过setItemDelegate函数调用委托

        在选择模型的使用-CSDN博客的MainWindow的构造函数中添加

    SpinBoxDelegate *delegate = new SpinBoxDelegate(this);
    table_view_->setItemDelegate(delegate);
//spinboxdelegate.h
#ifndef SPINBOXDELEGATE_H
#define SPINBOXDELEGATE_H

#include <QItemDelegate>

//继承自QItemDelegate,不需要编写自定义的显示函数
//编辑完成后,委托应该为其他组件提供提示。可以通过发射colseEditor()信号时使用合适的提示,它们会被构造编辑器时安装的默认QItemDelegate事件过滤器捕获。
//对于QItemDelegate提供的默认的事件过滤器,如果用户在spinbox编辑器中按下回车键,那么委托就会向模型提交数值,然后关闭编辑器。
class SpinBoxDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    explicit SpinBoxDelegate(QObject *parent = nullptr);

    //管理编辑器部件
    //创建编辑器,为视图提供编辑器部件
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
    //为编辑器设置数据
    void setEditorData(QWidget *editor, const QModelIndex &index) const override;
    //将数据写入到模型,当完成对部件数据的编辑,调用此函数告知委托将编辑好的数据存储到模型中
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;
    //更新编辑几何布局
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
};

#endif // SPINBOXDELEGATE_H
//spinboxdelegate.cpp
#include "spinboxdelegate.h"
#include <QSpinBox>

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 *spin_box = static_cast<QSpinBox*>(editor);
    spin_box->interpretText();//确保获得的是QSpinBox中最近更新的数值
    int value = spin_box->value();
    model->setData(index, value, Qt::EditRole);
}

void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);//使用了项目的矩形
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值