c++ - How to programmatically click a QPushButton

ID : 274301

viewed : 44

Tags : c++qtc++





Top 4 Answer for c++ - How to programmatically click a QPushButton

vote vote

93

Use QAbstractButton::animateClick():

QPushButton* startButton = new QPushButton("Start"); startButton->animateClick(); 
vote vote

82

RA's answer provides the way to do it so that it's visible that the button was clicked. If all you wish for is to emit the signal, what you're doing is correct in Qt 5, where the signals are public.

The error you're facing indicates that you're using Qt 4, where the signals are not public. You can work around this by invoking the signal indirectly:

QMetaObject::invokeMethod(ui->startButton, "clicked"); 

This calls the method immediately, i.e. the signal will be dispatched and the slots called by the time invokeMethod returns. Alas, most code (mostly your code!) assumes that the signal is emitted from event processing code close to the event loop - i.e. it's not reentrant, rather than from your own code. Thus you should defer the signal emission to the event loop:

// Qt 5.4 & up QTimer::singleShot(0, ui->startButton, [this]{ ui->startButton->clicked(); }); // Qt 4/5 QTimer::singleShot(0, ui->startButton, "clicked"); 

The following is a complete example for Qt 5.4 & up:

#include <QtWidgets>  int main(int argc, char ** argv) {    bool clicked = {};    QApplication app{argc, argv};    QPushButton b{"Click Me"};    QObject::connect(&b, &QPushButton::clicked, [&]{ clicked = true; qDebug() << "clicked"; });    Q_ASSERT(!clicked);    b.clicked(); // immediate call    Q_ASSERT(clicked);    clicked = {};    // will be invoked second - i.e. in connect order    QObject::connect(&b, &QPushButton::clicked, &app, &QApplication::quit);    QTimer::singleShot(0, &b, [&]{ b.clicked(); }); // deferred call    Q_ASSERT(!clicked);    app.exec();    Q_ASSERT(clicked);        } 
vote vote

70

If you do not want the animation stuff, you can also just call the method:

on_startButton_clicked(); 
vote vote

68

Top 3 video Explaining c++ - How to programmatically click a QPushButton







Related QUESTION?