QComboBox + QListWidget

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QComboBox>

namespace Ui {
class Dialog;
}

class QListWidget;
class ComboBox : public QComboBox
{
    Q_OBJECT

public:
    explicit ComboBox(QWidget *parent = 0);
    void updateData();

protected:
    void hidePopup();
    void showPopup();

private:
    QListWidget *m_listWidget;
};

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

private:
    Ui::Dialog *ui;
    QListWidget *m_listWidget;
};

#endif // DIALOG_H

#include "dialog.h"
#include "ui_dialog.h"
#include <QtWidgets>

ComboBox::ComboBox(QWidget *parent)
    : QComboBox(parent)
{
    m_listWidget = new QListWidget(this);
    this->setModel(m_listWidget->model());
    this->setView(m_listWidget);

    m_listWidget->setStyleSheet("QListWidget{background:#ff0000;}");
    updateData();
}

// 解决垂直滚动条出现,多次popup时item错乱的问题
void ComboBox::hidePopup()
{
    m_listWidget->scrollToTop();
    QComboBox::hidePopup();
}

void ComboBox::showPopup()
{
    QComboBox::showPopup();
    m_listWidget->scrollToTop();
}

void ComboBox::updateData()
{
    m_listWidget->clear();
    const int count = 50;
    for (int i=0; i<count; i++) {
        QListWidgetItem *item = new QListWidgetItem(m_listWidget);
        if (i == count - 2) {
            item->setFlags(Qt::NoItemFlags);
            m_listWidget->setItemWidget(item, new QLabel("-------------------------"));
            item->setSizeHint(QSize(item->sizeHint().width(), 10));
        } else if (i == count - 1) {
            QWidget *widget = new QWidget();
            QHBoxLayout *mainLayout = new QHBoxLayout();
            mainLayout->setContentsMargins(0, 0, 0, 0);
            mainLayout->addStretch();
            mainLayout->addWidget(new QLabel("+ 新建分组"));
            mainLayout->addStretch();
            widget->setLayout(mainLayout);
            m_listWidget->setItemWidget(item, widget);
            item->setSizeHint(QSize(item->sizeHint().width(), 25));
        } else {
            item->setText(QString::number(i * 1000));
        }
    }
}

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete ui;
}



你可能感兴趣的:(QComboBox + QListWidget)