自定义代理编辑控件类TComboBoxDelegate

自定义代理编辑控件是在tableView单元格中,呈现编辑辅助的Combox控件

自定义代理编辑控件类TComboBoxDelegate的定义过程

重写自定义代理编辑组件类的四个方法:  创建编辑组件、模型赋值给代理编辑组件、代理编辑组件数据到模型、更新位置

.h

#ifndef TCOMBOBOXDELEGATE_H
#define TCOMBOBOXDELEGATE_H

#include <QObject>
#include <QStyledItemDelegate>


class TComboBoxDelegate : public QStyledItemDelegate
{
    Q_OBJECT
private:
    QStringList m_itemList;
    bool m_editable;
public:
    explicit TComboBoxDelegate(QObject *parent = nullptr);

    void setItems(QStringList items,bool editable);

    QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) 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;


};

#endif // TCOMBOBOXDELEGATE_H

.cpp

#include "tcomboboxdelegate.h"
#include <QComboBox>

TComboBoxDelegate::TComboBoxDelegate(QObject *parent)
    : QStyledItemDelegate{parent}
{


}

void TComboBoxDelegate::setItems(QStringList items, bool editable)
{
    m_itemList= items;
    m_editable = editable;
}

QWidget *TComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);//不需要 option 和index 参数
    QComboBox *editor = new QComboBox(parent);
    editor->setEditable(m_editable);
    for(int i=0;i<m_itemList.count();i++)
    {
        editor->addItem(m_itemList.at(i));
    }
    return editor;
}

void TComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString str= index.model()->data(index,Qt::EditRole).toString();
    QComboBox *combo = static_cast<QComboBox*>(editor);
    combo->setCurrentText(str);
}

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

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


TComBoxDelegate自定义编辑控件

总结

1. 统一继承自 QStyledItemDelegate

2. 根据Combox的特性,需要自定义QStringList ,是否可编辑 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值