gpt4 book ai didi

c++ - QComboBox:仅在展开时显示图标

转载 作者:行者123 更新时间:2023-12-01 23:32:58 36 4
gpt4 key购买 nike

从“正常”QCombobox

开始

enter image description here

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

enter image description here

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

我见过两种方法:附加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()));

关于c++ - QComboBox:仅在展开时显示图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58931094/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com