1

When using a QToolButton and the setDefaultAction(myAction) method, it will get the default actions properties

Reference:

If a tool button has a default action, the action defines the button's properties like text, icon, tool tip, etc.

So I try to overwrite the icon, calling setIcon on the QToolButton.

myAction.setIcon(...);
myToolButton->setDefaultAction(myAction);
myToolButton->setIcon(...);

But it myToolButton still has the Icon of myAction.

Is there a way to hold the default action but overwrite it's icon, only for the QToolButton, not for the action itself? In otherwords: How can the QToolButtons have different properties than its default action?

Sadık
  • 4,249
  • 7
  • 53
  • 89

2 Answers2

4

If you take a look at the source for QToolButton::setDefaultAction(QAction* action), it uses setIcon(action->icon()) to set the icon from the action you give it. You can override that icon manually by calling setIcon with your desired separate icon after you call setDefaultAction.

Edit:

Here's a quick example you can try. Maybe you can compare it to what you're currently doing or post an example of your own?

MainWindow.cpp

#include "MainWindow.hpp"
#include <QAction>
#include <QToolButton>

MainWindow::MainWindow(QWidget* parent) :
  QMainWindow(parent) {
  QAction* action = new QAction(QIcon(QStringLiteral("original.jpg")), QStringLiteral("Test Action"), this);
  QToolButton* toolButton = new QToolButton(this);
  toolButton->setDefaultAction(action);
  toolButton->setIcon(QIcon(QStringLiteral("new.jpg")));
}

MainWindow.hpp

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QWidget>

class MainWindow : public QMainWindow {
  Q_OBJECT

 public:
  explicit MainWindow(QWidget* parent = nullptr);
};

#endif // MAINWINDOW_H

main.cpp

#include "MainWindow.hpp"
#include <QApplication>

int main(int argc, char* argv[]) {
  QApplication a(argc, argv);
  MainWindow w;
  w.show();

  return a.exec();
}
Andrew Dolby
  • 799
  • 1
  • 13
  • 25
  • The reference docs you linked were for Qt 4.8, so I checked the source for 4.8. It's got the same use of `setIcon(action->icon())`. Could you post a more complete code example? I've tested using `setDefaultAction` then `setIcon`, and it's working for me. I'll post an example if you'd like to take a look. – Andrew Dolby Aug 22 '14 at 17:48
  • your code works for me. However my code doesn't and I don't understand why. Anyhow, it seems that I have another problem here. – Sadık Aug 26 '14 at 10:20
1

QToolButton icon will reset to action icon when action changed.

We need re-override code like this;

connect(toolButton, &QAction::changed, [=](){
   toolButton->setIcon(QIcon(QStringLiteral("new.jpg")));
});
HighLow
  • 11
  • 1