我有QToolButton
和一对QAction
s里面。
问题是我已经为这个工具栏按钮设置了一个图标,我不想让它改变,当我从弹出式菜单中选择一些QAction
(它将设置项更改为所选QAction
的文本)。有什么方法可以让我得到我需要的东西吗?
头文件
#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
源代码中挖掘了一点,看起来这种行为是硬编码的,因为QToolButton
类侦听triggered
动作信号并相应地更新按钮默认动作(QToolButton::setDefaultAction)
您可能可以连接到相同的信号,并按您的意愿重置QToolButton图标。
顺便说一句,这看起来是一个相当明智的行为,因为您的操作是可检查的,并包装在QToolButton中。
是的,这是可能的,正如alediaferia建议的,你可以先保存QToolButton图标,然后重新设置它:
QObject::connect(this, &QToolButton::triggered, [this](QAction *triggeredAction) {
QIcon icon = this->icon();
this->setDefaultAction(triggeredAction);
this->setIcon(icon);
});
PS:如果你想使用我的代码不要忘记启用c++11支持lambda表达式在您的配置文件中添加CONFIG += c++11