How to programmatically press QPushButton

I am using Qt. I have a button on a page added through Qt Creator. It is associated with the void MyPage::on_startButton_clicked() method void MyPage::on_startButton_clicked() .

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

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

Please, help. Thanks!

+7
c ++ qt
source share
3 answers

Use QAbstractButton::animateClick() :

 QPushButton* startButton = new QPushButton("Start"); startButton->animateClick(); 
+16
source share

The RA answer provides a way to do this so that it is visible that the button is pressed. If all you want is to emit a signal, then you are doing it right in Qt 5, where the signals are publicly available.

The error you encounter indicates that you are using Qt 4 where the signals are not publicly available. You can get around this by indirectly touching the signal:

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

This immediately calls the method, that is, the signal will be sent, and the slots called by the invokeMethod time will return. Alas, most of the code (basically your code!) Assumes that the signal is emitted from an event processing code close to the event loop, i.e. Not reentrant, not from your own code. Thus, you should defer signal emission in 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"); 

Below is a complete example for Qt 5.4 and higher:

 #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 - ie 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); } 
+7
source share

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

 on_startButton_clicked(); 
0
source share

All Articles