【问题标题】:Fix QToolButton icon修复 QToolButton 图标
【发布时间】:2015-05-29 09:49:44
【问题描述】:

我有QToolButton,里面有一对QActions。
问题是我已经为这个工具栏按钮设置了一个图标,我不希望它改变,当我选择一些QAction时(它将设置项目从选定的QAction更改为文本)从弹出菜单。
是否有任何 qt 方式来获得我需要的东西?

头文件

#include <QToolButton>

class FieldButton : public QToolButton
{
    Q_OBJECT
public:
    explicit FieldButton(QWidget *parent = 0);
};



cpp 文件

 #include "fieldbutton.h"

FieldButton::FieldButton(QWidget *parent) :
    QToolButton(parent)
{
    setPopupMode(QToolButton::MenuButtonPopup);
    QObject::connect(this, SIGNAL(triggered(QAction*)),
                     this, SLOT(setDefaultAction(QAction*)));
}


我就是这样使用它的:

FieldButton *fieldButton = new FieldButton();
QMenu *allFields = new QMenu();
// ...  filling QMenu with all needed fields of QAction type like:
QAction *field = new QAction(tr("%1").arg(*h),0);
field->setCheckable(true);
allFields->addAction(field);
// ...
fieldButton->setMenu(allFields);
fieldButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
fieldButton->setIcon(QIcon(":/field.png"));
fieldButton->setText("My text");
fieldButton->setCheckable(true);
toolbar->addWidget(fieldButton);

【问题讨论】:

  • 你能分享你用来设置 QToolButton 和里面的 QAction 的代码吗?
  • 也许您可以使用自定义样式表覆盖按钮的图标?以此为灵感:stackoverflow.com/questions/20573944/…
  • @alediaferia 我提供了代码

标签: qt qaction qtoolbutton


【解决方案1】:

所以,我在QToolButton 源代码here 中挖掘了一点,看起来这种行为是硬编码的,因为QToolButton 类侦听动作triggered 信号并更新按钮默认动作相应地 (QToolButton::setDefaultAction)

您可以随意连接到相同的信号并重置 QToolButton 图标。

顺便说一句,鉴于您的操作是可检查的并且包装在 QToolButton 中,这看起来是一种相当明智的行为。

【讨论】:

    【解决方案2】:

    是的,正如 alediaferia 建议的那样,您可以先保存 QToolButton 图标并再次重置它:

     QObject::connect(this, &QToolButton::triggered, [this](QAction *triggeredAction) {
            QIcon icon = this->icon();
            this->setDefaultAction(triggeredAction);
            this->setIcon(icon);
     });
    

    PS:如果您想使用我的代码,请不要忘记通过添加 CONFIG += c++11 在您的 pro 文件中启用 c++11 对 lambda 表达式的支持

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多