《QTreeView中嵌入QComboBox实现选择数据》:系列教程之八(第4小节)

本小节属于《QTreeView使用代理实现表项编辑、定制显示控件》:系列教程之八的子章节。

由于本章节内容较多,放在一起可能大家看起来比较费劲,所以进行了拆分,大家可以从这里《QTreeView使用系列教程目录》找到其他的小节内容。


接下来开始讲解,QTreeView中嵌入QComboBox实现选择数据。

从委托类QItemDelegate继承,

createEditor()创建Editor并返回,

setEditorData()用于初始化Editor数据,

setModelData()用于Editor修改数据后写回model,

updateEditorGeometry()用于设置Editor位置。

class ComboBoxDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    ComboBoxDelegate(QObject *parent = nullptr)
        : QItemDelegate(parent) { }

    void setItems(const QStringList &texts) { _texts = texts; }

public:
    QWidget *createEditor(QWidget *parent,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const override
    {
        QComboBox *editor = new QComboBox(parent);
        editor->addItems(_texts);
        return editor;
    }

    void setEditorData(QWidget *editor, const QModelIndex &index) const override
    {
        QString text = index.model()->data(index, Qt::EditRole).toString();
        QComboBox *comboBox = static_cast<QComboBox*>(editor);
        int tindex = comboBox->findText(text);
        comboBox->setCurrentIndex(tindex);
    }

    void setModelData(QWidget *editor,
                      QAbstractItemModel *model,
                      const QModelIndex &index) const override
    {
        QComboBox *comboBox = static_cast<QComboBox*>(editor);
        QString text = comboBox->currentText();
        model->setData(index, text, Qt::EditRole);
    }

    void updateEditorGeometry(QWidget *editor,
                               const QStyleOptionViewItem &option,
                               const QModelIndex &index) const override
    {
        editor->setGeometry(option.rect);
    }

private:
    QStringList _texts;
};

给第3列指定委托,那么第3列使用QComboBox修改数据。

ComboBoxDelegate* comboBox = new ComboBoxDelegate(ui->treeView);
comboBox->setItems(QStringList()<<"支出"<<"收入");
ui->treeView->setItemDelegateForColumn(3, comboBox);

效果:
在这里插入图片描述



若对你有帮助,欢迎点赞、收藏、评论,你的支持就是我的最大动力!!!

同时,阿超为大家准备了丰富的学习资料,欢迎关注公众号“超哥学编程”,即可领取。

本文涉及工程代码,公众号回复:34EditorDelegate,即可下载。

在这里插入图片描述

  • 0
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值