QComboBox结合QCheckBox实现下拉列表复选框功能

QCheckboxCombo.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <QComboBox>
#include <QListView>

class QCheckboxCombo : public QComboBox
{
    Q_OBJECT
public:
    explicit QCheckboxCombo(QWidget *parent = nullptr);
    bool eventFilter(QObject * watched, QEvent * event) override;
    void hidePopup() override;
    void showPopup() override;
    void setDelimiter(QString str){ _delimiter = str; }

private:
    QString _delimiter = ",";

signals:
    void beforeOpen();
};

QCheckboxCombo.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "qcheckboxcombo.h"
#include <QMouseEvent>
#include <QDebug>

QCheckboxCombo::QCheckboxCombo(QWidget *parent) :
    QComboBox(parent)
{
    view()->viewport()->installEventFilter(this);
    setEditable(true);
}

bool QCheckboxCombo::eventFilter(QObject * watched, QEvent * event)
{
    if (event->type() == QEvent::MouseButtonRelease)
    {
        QModelIndex ind = view()->indexAt(((QMouseEvent*)event)->pos());
        bool checked = view()->model()->data(ind, Qt::CheckStateRole).toBool();
        view()->model()->setData(ind, !checked, Qt::CheckStateRole);
        return true;
    }
    return QObject::eventFilter(watched, event);
}

void QCheckboxCombo::hidePopup()
{
    QStringList values;
    for (int i=0; i < count(); i++){
      if (itemData(i, Qt::CheckStateRole).toBool()){
        values << itemText(i);
      }
    }
    setCurrentText(values.join(_delimiter));

    QComboBox::hidePopup();
}

void QCheckboxCombo::showPopup()
{
    QStringList values = currentText().split(_delimiter);

    emit beforeOpen();

    for (int i=0; i<count(); i++){
      setItemData(i, values.contains(itemText(i)), Qt::CheckStateRole);
    }
    QComboBox::showPopup();
}
1
2
3
4
5
6
7
8
9
10
QCheckboxCombo *combo = new QCheckboxCombo;
combo->setFixedSize(200, 30);
combo->addItem(tr("Once"));
combo->setItemIcon(0, QIcon("C:\\Users\\wangjun\\Downloads\\test.png"));
combo->addItem(tr("Twice"));
combo->setItemIcon(1, QIcon("C:\\Users\\wangjun\\Downloads\\test.png"));
combo->addItem(tr("Thrice"));
combo->setItemIcon(2, QIcon("C:\\Users\\wangjun\\Downloads\\test.png"));
ui->frame->layout()->addWidget(combo);
new QHBoxLayout(ui->frame);