Qt5/C++: change style of a QIcon inside a QToolBar

753 views Asked by At

I'm adding actions to a QToolBar only using icons and an empty text, and I want to change each action style when it is triggered (specifically, changing its border color):

toolbar = new QToolBar;
action1 = toolbar->addAction(my_icon1, "");
action2 = toolbar->addAction(my_icon2, "");

QObject::connect(action1, &QAction::triggered, [this]{
    // change border color of action1
    // unset border color of action2
});

QObject::connect(action2, &QAction::triggered, [this]{
    // change border color of action2
    // unset border color of action1
});

But since a QIcon is not a widget (not a QAction of course), I don't know where to set the style of a specific action, and QAction::associatedWidget() returns the QToolBar widget and not the associated button that owns the icon.

I'm using only C++ code, without QML or ui files.

1

There are 1 answers

0
ABu On

Since QAction::parentWidget and QAction::associatedWidgets both contain the QToolBar instead of the actual action widget, I didn't give initial credit to QToolBar::widgetForAction (I thought it would be some kind of convenient function for the QAction:: methods above). But it deserves it, because it returns the actual widget for that action, as the function name says:

toolbar->widgetForAction(action1)->setStyleSheet
    ("QWidget { border: 1px solid blue; }");