【问题标题】:Hide Icon from the label of QComboBox从 QComboBox 的标签中隐藏图标
【发布时间】:2017-08-07 11:45:23
【问题描述】:

我正在尝试实现一个QComboBox,其中包含QIconQString,如下所示:

QComboBox.addItem(icon, label);

我希望图标在下拉列表中可见,但在工具栏中不可见。选择项目后,只有字符串应该是可见的。

有没有简单的方法可以做到这一点?

【问题讨论】:

  • 简单(但有点hackish):重新实现showPopuphidePopup,并根据需要添加/删除图标。
  • @ekhumoro 这可能不适用于我的方案,因为在任何一种情况下,我都不希望图标在工具栏中可见。如果我在showPopup中实现,prev选择会在工具栏中显示图标,这不是我想要的。

标签: c++ qt pyqt4 qcombobox


【解决方案1】:

要解决这个问题,重写paintEvent方法就足够了,从源代码中获取默认实现。在绘制控件QStyle::CE_ComboBoxLabel之前,需要设置QStyleOptionComboBox.currentIcon的无效值

如果组合框不可编辑,这很有效,否则左侧有一个空白区域用于绘制图标。查看源代码,我发现组合框改变了QLineEdit 的几何形状。如果当前元素有一个图标,那么几何上QLineEdit 将向右移动。为了防止在同一个paintEvent中出现这种情况,需要在不考虑图标的情况下强制QLineEdit的几何形状。

以下代码考虑到了这一点,并且在两种模式下都能正常工作:

class ComboBox : public QComboBox {
public:
    ComboBox(QWidget *parent = nullptr)
        : QComboBox(parent) {  }

protected:
    void paintEvent(QPaintEvent *) override {
        QStylePainter painter(this);
        painter.setPen(palette().color(QPalette::Text));

        // draw the combobox frame, focusrect and selected etc.
        QStyleOptionComboBox opt;
        initStyleOption(&opt);
        painter.drawComplexControl(QStyle::CC_ComboBox, opt);

        // draw the icon and text
        opt.currentIcon = QIcon();
        if (auto le = lineEdit()) {
            le->setGeometry(style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxEditField, this));
        } else {
            painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
        }
    }
};

【讨论】:

    【解决方案2】:

    最好的方法是设置一个委托并自己绘制项目。 然后你可以选择何时或不绘制图标(装饰角色),你可以选择不为当前索引的索引绘制图标。 我可以找到一个关于如何在组合框上使用委托的快速示例: http://programmingexamples.net/wiki/Qt/Delegates/ComboBoxDelegate

    但恐怕这不是最简单的方法。 祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多