qt6 学习笔记 01

53 阅读1分钟

信号槽

头文件必须有 Q_OBJECT 这个宏

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class Widget : public QWidget
{
    Q_OBJECT  // 确保添加这一行
public:
    explicit Widget(QWidget *parent = nullptr);

signals:

public slots:

    void login_clicked();
};

#endif // WIDGET_H

代码体

#include "widget.h"
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QDebug>


QLineEdit *username;
QLineEdit *password;

Widget::Widget(QWidget *parent)
    : QWidget{parent}
{
    QLabel *labelUsername = new QLabel("Username");
    QLabel *labelPassword = new QLabel("Password");

    username = new QLineEdit();
    password = new QLineEdit();
    password->setEchoMode(QLineEdit::Password);

    QPushButton *loginButton = new QPushButton("Sign In");

    // connect(loginButton, SIGNAL(clicked()), this, SLOT(login_clicked()));
    connect(loginButton, &QPushButton::clicked, this, &Widget::login_clicked);

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(labelUsername);
    layout->addWidget(username);
    layout->addWidget(labelPassword);
    layout->addWidget(password);
    layout->addWidget(loginButton);

    this->setLayout(layout);
}

void Widget::login_clicked(){
    QString un = username->text();
    QString pd = password->text();

    if (un == QString("milo") && pd == QString("milo")) {
        qDebug() << "sign in successfully";
    } else {
        qDebug() << "sign in failed";
    }
}

绑定信号槽的两种形式:

    // connect(loginButton, SIGNAL(clicked()), this, SLOT(login_clicked()));
    connect(loginButton, &QPushButton::clicked, this, &Widget::login_clicked);