我有QToolButton,里面有几个QAction。
问题是,我已经为这个工具栏按钮设置了一个图标,当我从弹出式菜单中选择一些QAction (它从选定的QAction中将set项更改为文本)时,我不希望它改变。
有什么办法让我得到我需要的东西吗?
头文件
#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);发布于 2015-05-29 10:19:28
因此,我在QToolButton源代码这里中做了一些研究,看起来这种行为是硬编码的,因为QToolButton类监听动作triggered信号,并相应地更新按钮默认操作(QToolButton::setDefaultAction)。
您可能可以连接到相同的信号,并重置QToolButton图标根据您的意愿。
顺便说一句,这看起来是相当明智的行为,因为您的操作是可检查的,并且包装在QToolButton中。
发布于 2015-05-29 20:03:03
是的,这是可能的,就像艾狄达菲所建议的那样,你可以先保存QToolButton图标,然后重新设置它:
QObject::connect(this, &QToolButton::triggered, [this](QAction *triggeredAction) {
QIcon icon = this->icon();
this->setDefaultAction(triggeredAction);
this->setIcon(icon);
});PS:如果您想使用我的代码,请通过添加CONFIG += c++11,在pro文件中启用对lambda表达式的+=支持。
https://stackoverflow.com/questions/30526439
复制相似问题