Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically click a QPushButton

Tags:

c++

qt

I am using Qt. I have a button in the page added via the Qt Creator. It is connected to the method void MyPage::on_startButton_clicked().

I want to programmatically click this button. I tried ui->startButton->clicked(), it gives,

error C2248: 'QAbstractButton::clicked' : cannot access protected member declared in class 'QAbstractButton'

Please help. Thanks!

like image 565
PDH Avatar asked May 13 '14 01:05

PDH


2 Answers

Use QAbstractButton::animateClick():

QPushButton* startButton = new QPushButton("Start");
startButton->animateClick();
like image 136
RA. Avatar answered Nov 20 '22 06:11

RA.


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);       
}
like image 9
Kuba hasn't forgotten Monica Avatar answered Nov 20 '22 04:11

Kuba hasn't forgotten Monica