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 prog
If you do not want the animation stuff, you can also just call the method:
on_startButton_clicked();
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);
}
Use QAbstractButton::animateClick():
QPushButton* startButton = new QPushButton("Start");
startButton->animateClick();