QComboBox:展开时只显示图标

QComboBox: Only show the icons when expanded

从 "normal" QCombobox

开始

我想要一个 QCombobox 只在展开时显示图标,但在折叠时不显示的图标。

我找到了几个类似问题的答案,但它们都显示了更复杂情况下的代码,我还没有设法提炼出它的核心。

我见过两种方法:附加 QListView 或使用 QItemDelegate(或两者)。

但是我找不到任何直截了当的示例代码。

这是我的起点点:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->iconsComboBox->addItem(QIcon(":/icons/1.png"), "red");
    ui->iconsComboBox->addItem(QIcon(":/icons/2.png"), "green");
    ui->iconsComboBox->addItem(QIcon(":/icons/3.png"), "pink");

    auto quitAction = new QAction();
    quitAction->setShortcuts(QKeySequence::Quit);
    addAction(quitAction);
    connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
}

那个阶段的完整工作代码在这里:https://github.com/aoloe/cpp-qt-playground-qcombobox/tree/simple-qcombobox

如何在QCombobox关闭时隐藏图标?


我已经接受了 eyllanesc 的两个拉取请求:

您可以获得代码并运行它以查看实际效果。

一种可能的解决方案是覆盖 paintEvent 方法:

##ifndef COMBOBOX_H
#define COMBOBOX_H

#include <QComboBox>
#include <QStylePainter>

class ComboBox : public QComboBox
{
public:
    using QComboBox::QComboBox;
protected:
    void paintEvent(QPaintEvent *)
    {
        QStylePainter painter(this);
        painter.setPen(palette().color(QPalette::Text));
        // draw the combobox frame, focusrect and selected etc.
        QStyleOptionComboBox opt;
        initStyleOption(&opt);
        <b>opt.currentIcon = QIcon();
        opt.iconSize = QSize();</b>
        painter.drawComplexControl(QStyle::CC_ComboBox, opt);
        // draw the icon and text
        painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
    }

};

#endif // COMBOBOX_H

如果您想在 .ui 中使用它,那么您必须 promote it.


另一种可能的解决方案是使用 QProxyStyle

#ifndef COMBOBOXPROXYSTYLE_H
#define COMBOBOXPROXYSTYLE_H

#include <QProxyStyle>

class ComboBoxProxyStyle : public QProxyStyle
{
public:
    using QProxyStyle::QProxyStyle;
    void drawControl(QStyle::ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *w) const
    {
        if(element == QStyle::CE_ComboBoxLabel){
            if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
                QStyleOptionComboBox cb_tmp(*cb);
                cb_tmp.currentIcon = QIcon();
                cb_tmp.iconSize = QSize();
                QProxyStyle::drawControl(element, &cb_tmp, p, w);
                return;
            }
        }
        QProxyStyle::drawControl(element, opt, p, w);
    }
};

#endif // COMBOBOXPROXYSTYLE_H
ui->iconsComboBox->setStyle(new ComboBoxProxyStyle(ui->iconsComboBox->style()));