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); }
Kuba ober
source share