Sadık
Sadık

Reputation: 4419

QToolButton should have another icon than the default action

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?

Upvotes: 1

Views: 4275

Answers (2)

HighLow
HighLow

Reputation: 11

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")));
});

Upvotes: 1

Andrew Dolby
Andrew Dolby

Reputation: 809

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();
}

Upvotes: 4

Related Questions