【问题标题】:QComboBox: Only show the icons when expandedQComboBox:仅在展开时显示图标
【发布时间】:2019-11-19 09:52:17
【问题描述】:

从“正常”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 的两个拉取请求:

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

【问题讨论】:

标签: c++ qt qcombobox


【解决方案1】:

一种可能的解决方案是重写paintEvent方法:

##ifndef COMBOBOX_H
#define COMBOBOX_H

#include &ltQComboBox>
#include &ltQStylePainter>

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);
        opt.currentIcon = QIcon();
        opt.iconSize = QSize();
        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()));

【讨论】:

  • 感谢@eyllanesc 的回答。我不确定这是最简单的解决方案。我目前正在探索QItemDelegate 的用法,稍后将按照您的建议尝试使用自定义ComboBox,然后回来告诉您它是如何工作的。
  • @a.l.e 我已经对你的 repo 做了一个 PR,所以你可以轻松地测试它。 QItemDelegate 仅用于修改显然无法解决您的问题的弹出窗口。
猜你喜欢
  • 1970-01-01
  • 2016-03-22
  • 2021-06-13
  • 2018-05-15
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多