Reputation: 4125
In Qt when we use the function addAction
of a QToolBar
:
_LastBar->addAction(QtExtensions::Action(name, icon, func));
How could we retrieve the QToolButton
generated for that action?
Or, if this is not possible, how to find the last button/widget of a QToolBar
?
Upvotes: 5
Views: 3795
Reputation: 20151
I found the following method which sounds promising: QToolbar::widgetForAction()
.
The QToolbar::addAction()
returns a QAction*
with the pointer of created QAction
instance. This pointer is used with QToolbar::widgetForAction()
and should return the corresponding QWidget*
. Knowing that this should be a QToolButton
we can apply a dynamic_cast<QToolButton*>
which shouldn't fail.
To check this out, the following MCVE testQToolBarAddAction.cc
:
#include <QtWidgets>
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
QToolBar qToolBar;
QAction *pQAction = qToolBar.addAction(
"Click Me", [](bool) { qDebug() << "Clicked."; });
QToolButton *pQToolBtn
= dynamic_cast<QToolButton*>(qToolBar.widgetForAction(pQAction));
qDebug() << "QToolbutton::label:" << pQToolBtn->text();
qToolBar.show();
return app.exec();
}
testQToolBarAddAction.pro
:
SOURCES = testQToolBarAddAction.cc
QT = widgets
Compiled and tested on cygwin:
$ qmake-qt5 testQToolBarAddAction.pro
$ make
$ ./testQToolBarAddAction
Qt Version: 5.9.4
QToolbutton::label: "Click Me"
Clicked.
The QToolButton
returns the same label like the QAction
– which should count as proof.
Upvotes: 11