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?

Sturm
  • 3,968
  • 10
  • 48
  • 78
  • 1
    This sounds promising: [`QToolbar::widgetForAction()`](http://doc.qt.io/qt-5/qtoolbar.html#widgetForAction). You may feed it with the `QAction*` returned by `addAction()` and `dynamic_cast()` the result. – Scheff's Cat Sep 05 '18 at 08:48

1 Answers1

9

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.

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56