信号和槽

信号和槽之间的连接,实现对象间的通信。

  • 信号是一个发出的动作或事件。

  • 槽是对应的响应动作。

  • 一个信号可以关联多个槽函数,信号也可以连接信号

  • 使用信号槽,类必须继承QObject。在类的定义开头需要添加宏定义Q_OBJECT

实现方式

  • 通过函数指针连接
connect(sender, SIGNAL(signal()), receiver, SLOT(slot()));
//参数1 发送者
//参数2 发出的信号
//参数3 接收者
//参数4 槽(用来响应)

新的语法

connect(sender, &SenderClass::signal, receiver, &ReceiverClass::slot);

断开连接:

disconnect(sender, &SenderClass::signal, receiver, &ReceiverClass::slot);

使用自定义信号和槽

class MyWidget : public QWidget {
    Q_OBJECT
public:
    // 自定义信号
    void customSignal(int value);

private slots:
    // 自定义槽函数
    void customSlot(int value);
};
connect(sender, &SenderClass::customSignal, receiver, &ReceiverClass::customSlot);

简单的例子

#include "mainwindow.h"

#include <QApplication>
#include <QDebug>
#include <QtWidgets/QtWidgets>
class CounterApp:public QWidget{

public:
    CounterApp(QWidget *parent = nullptr) : QWidget(parent) {
        count =110;
        // 创建界面元素
        QVBoxLayout *layout = new QVBoxLayout;
        QLabel *label = new QLabel("点击次数:");
        QPushButton *button = new QPushButton("增加");
        // 将按钮的点击信号连接到自定义的槽函数
        connect(button, &QPushButton::clicked, this, &CounterApp::incrementCount);

        // 将界面元素添加到布局
        layout->addWidget(label);
        layout->addWidget(button);
        setLayout(layout);
    }

private slots:
    void incrementCount() {
        count++;
        qDebug()<<"count"<<count;
    }

private:
    int count;
};
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CounterApp c ;
    c.show();
    return a.exec();
}