yui amanda
yui amanda

Reputation: 17

How to attach event click to button Qt?

I try to attach event click to button. For testing, i just want to change button text when click.

as I read from doc https://doc.qt.io/qt-5/qobject.html. All QWidgets inherit QObject. Thats means all widget avaiable for signal and slot. Include this QPushButton.

But text in button not change. whats problem?

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QObject>

int main(int argc, char *argv[]) {
    
    QApplication app(argc, argv);
    
    QWidget *window = new QWidget;
    window->setWindowTitle("Pandora");
    window->setFixedSize(640, 360);

    QVBoxLayout *layout = new QVBoxLayout(window);

    QPushButton *login = new QPushButton;
    login->setText("Login");

    QObject::connect(login, SIGNAL(clicked()), login, SLOT(setText("Change Success")));
    
    
    layout->addWidget(login);

    window->show();

    return app.exec();
}

Upvotes: 0

Views: 1851

Answers (1)

RA.
RA.

Reputation: 7767

To begin with, the specific values of arguments can not be specified when creating a signal-slot connection. So "Change Success" is not permitted. You are likely getting an error message on the console indicating that no such slot exists. The correct syntax is to indicate the argument type, not the value (e.g., SLOT(setText(QString))).

Secondly, the arguments of the signal and the slot must be compatible. In this case, the clicked() signal provides no arguments and thus can not be connected to the setText(QString) slot.

Thirdly, you are using the legacy string-based connection syntax for signal-slot connections. The functor-based syntax is preferred (refer to https://doc.qt.io/qt-5/signalsandslots-syntaxes.html).

The quickest way to change the button text with a signal-slot connection is to use the functor syntax with a lambda (requires Qt5+):

connect(login, &QPushButton::clicked, [=]() { login->setText("Change Success"); });

Upvotes: 3

Related Questions