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