博客
关于我
Qt信号和槽--对象之间的通信
阅读量:166 次
发布时间:2019-02-28

本文共 1745 字,大约阅读时间需要 5 分钟。

Qt中最显著的特点之一就是其信号槽机制。这种机制使得对象之间能够高效地通信和传递消息,在前台界面开发中尤其常见。通过信号槽机制,程序可以在不直接访问对象的情况下,实现跨对象的通信,这种设计方式大大提升了代码的可维护性和复用性。

要将两个对象关联起来,可以使用connect函数。具体而言,信号发送者(sender)通过发送特定信号,触发接收者的相应槽函数(method)。QObject::connect方法的定义如下:

QMetaObject::Connection QObject::connect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection)

以下是一个简单的示例:

头文件

#ifndef SIGNALSLOTDEMO_H#define SIGNALSLOTDEMO_H#include 
class SignalSlotDemo : public QObject { Q_OBJECTpublic: explicit SignalSlotDemo(QObject *parent = 0); int getValue(); signals: void changedValue(int newValue);public slots: void setValue(int value);private: int value;};#endif // SIGNALSLOTDEMO_H

源文件

#include "signalslotdemo.h"#include 
using namespace std;SignalSlotDemo::SignalSlotDemo(QObject *parent) : QObject(parent), value() {}int SignalSlotDemo::getValue() { return this->value;}void SignalSlotDemo::setValue(int value) { this->value = value; emit changedValue(this->value);}int main() { // ...(其他代码) return 0;}

测试文件

#include 
#include
using namespace std;#include "signalslotdemo.h"int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); SignalSlotDemo demo1; SignalSlotDemo demo2; QObject::connect(&demo1, SIGNAL(changedValue(int)), &demo2, SLOT(setValue(int))); demo1.setValue(200); cout << demo2.getValue() << endl; return 0;}

代码解释

在这个示例中,SignalSlotDemo类定义了一个名为changedValue的信号和一个名为setValue的槽函数。通过connect方法,我们将demo1changedValue信号与demo2setValue槽函数关联起来。当demo1调用setValue时,它会发射一个携带valuechangedValue信号,触发demo2setValue槽函数,从而实现了跨对象的通信。

这种设计模式使得代码更加模块化,各部分之间的耦合度降低,提高了代码的可维护性和扩展性。同时,信号槽机制也为前台界面开发提供了更直观的用户体验。

转载地址:http://uzfc.baihongyu.com/

你可能感兴趣的文章
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>
Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
查看>>
nodejs libararies
查看>>
nodejs-mime类型
查看>>
nodejs中Express 路由统一设置缓存的小技巧
查看>>
Node入门之创建第一个HelloNode
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>