简体   繁体   中英

How to programmatically click a QPushButton

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!

Use QAbstractButton::animateClick() :

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

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, ie 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 - ie 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);       
}

如果你不想要动画的东西,你也可以调用这个方法:

on_startButton_clicked();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM