Qt之QComboBox下拉框实现勾选

QComboBox下拉界面带勾选


1、前言

QComboBox每次只能选择一个,现项目中需要可以多次勾选,不想基于第三方库qxtlib进行开发,所以自己参考qxtcheckcombobox源码,在此基础上进行修改。可保持QComboBox风格,不另行设置界面。


2、实现效果如下

在这里插入图片描述


3、思路

主体思路就是对于下拉的数据源model的数据标志位添加可勾选属性。
下面列举一些Qt::ItemDataRole

Constant Value Description
Qt::FontRole 6 The font used for items rendered with the default delegate. (QFont)
Qt::TextAlignmentRole 7 The alignment of the text for items rendered with the default delegate. (Qt::Alignment)
Qt::BackgroundRole 8 The background brush used for items rendered with the default delegate. (QBrush)
Qt::BackgroundColorRole 8 This role is obsolete. Use BackgroundRole instead.
Qt::ForegroundRole 9 The foreground brush (text color, typically) used for items rendered with the default delegate. (QBrush)
Qt::TextColorRole 9 This role is obsolete. Use ForegroundRole instead.
Qt::CheckStateRole 10 This role is used to obtain the checked state of an item. (Qt::CheckState)
Qt::InitialSortOrderRole 14 This role is used to obtain the initial sort order of a header view section. (Qt::SortOrder). This role was introduced in Qt 4.8.

4、代码干货

以下代码仅供参考,可根据实际需求修改

class DSCheckComboModel : public QStandardItemModel
{
	Q_OBJECT

public:
	explicit DSCheckComboModel(QObject* parent = Q_NULLPTR);

	virtual Qt::ItemFlags flags(const QModelIndex& index) const;
	virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
	virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);

Q_SIGNALS:
	void checkStateChanged();
};

class DSCheckComboBoxPrivate;
class DSCheckComboBox : public QComboBox
{
	Q_OBJECT

	Q_PROPERTY(QString separator READ separator WRITE setSeparator)
	Q_PROPERTY(QString defaultText READ defaultText WRITE setDefaultText)
	Q_PROPERTY(QStringList checkedItems READ checkedItems WRITE setCheckedItems)

public:
	DSCheckComboBox(QWidget *pa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值