简单理解QT中的信号和槽
信号和槽
信号和槽之间的连接,实现对象间的通信。
-
信号是一个发出的动作或事件。
-
槽是对应的响应动作。
-
一个信号可以关联多个槽函数,信号也可以连接信号
-
使用信号槽,类必须继承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();
}
本文作者:不会笑的孩子
本文链接:https://www.cnblogs.com/doubleconquer/p/17621567.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!