Qt QToolBar get button added by addAction
Asked Answered
R

1

5

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?

Rheinland answered 5/9, 2018 at 8:38 Comment(1)
This sounds promising: QToolbar::widgetForAction(). You may feed it with the QAction* returned by addAction() and dynamic_cast<QToolButton*>() the result.Nesta
N
11

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.

snapshot of testQToolBarAddAction

The QToolButton returns the same label like the QAction – which should count as proof.

Nutter answered 5/9, 2018 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.