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.
QToolbar::widgetForAction()
. You may feed it with theQAction*
returned byaddAction()
anddynamic_cast<QToolButton*>()
the result. – Nesta