Home > database >  QPushButton signal
QPushButton signal

Time:04-29

I'm trying to get a QPushButton's action method running doing the following.

My login.h:

//
// Created by simon on 28.04.22.
//

#ifndef RESTCLIENT_LOGIN_H
#define RESTCLIENT_LOGIN_H

#include <QWidget>
#include <QPushButton>
#include <QLineEdit>


QT_BEGIN_NAMESPACE
namespace Ui { class Login; }
QT_END_NAMESPACE

class Login : public QWidget {
Q_OBJECT

QPushButton * loginButton;
QLineEdit * passwordInput;
QLineEdit * usernameInput;
QObject::connect(loginButton, &QPushButton::click, this, &buttonPressed);

public slots:
    void buttonPressed();

public:
    explicit Login(QWidget *parent = nullptr);

    ~Login() override;

private:
    Ui::Login *ui;
};


#endif //RESTCLIENT_LOGIN_H

The corresponding login.cpp:

#include "login.h"
#include "ui_Login.h"


Login::Login(QWidget *parent) :
        QWidget(parent), ui(new Ui::Login) {
    ui->setupUi(this);
}

Login::~Login() {
    delete ui;
}

void Login::buttonPressed() {
    //todo process login
}

The build fails, and Clion marks the code line containing the connect method in red. I'm aware that my attempt to connect the signal to my function is wrong, I hope someone can help me.

CodePudding user response:

The issue is that QPushButton::click() is not a signal, it is a function that performs a click.

The signal emitted when clicking the button is: QPushButton::clicked().

And as already mentioned, you should call the QObject::connect() function from inside a function (in the constructor for example). It makes no sense to call it in the class declaration.

CodePudding user response:

The connect call looks mostly fine, except that click is not a signal as Fareanor first noticed in his answer; use the clicked signal from QPushButton's base class QAbstractButton instead. See also QAbstractButton Signals for all available signals.

Additionally, connect needs to be inside of a function, not in the class declaration. The button needs to be initialized for the connection to work, so the constructor of your Login class seems like a logical place for it, for example:

Login::Login(QWidget *parent) :
        QWidget(parent), ui(new Ui::Login) {
    ui->setupUi(this);
    QObject::connect(loginButton, &QPushButton::clicked, this, &buttonPressed);
}

From the code you're showing it seems that loginButton is separate from the other GUI stuff in ui, so you probably also need to create that button first, i.e., adding , loginButton(new QPushButton) after ui(...), or move the loginButton to your .ui file...

  • Related