Qt中的connect函数使用

本文详细介绍了Qt中connect函数的工作原理,包括SIGNAL和SLOT宏的定义、connect函数的实现,以及信号与槽的连接过程。通过示例和源码分析,揭示了连接过程中的参数转换和类型检查。
摘要由CSDN通过智能技术生成

我们在使用connect函数的时候一般是这样调用的:

[cpp]  view plain   copy
  1. connect(sender,SIGNAL(signal()),receiver,SLOT(slot()));  

这里用到了两个宏:SIGNAL() 和SLOT();通过connect声明可以知道这两个宏最后倒是得到一个const char*类型。
在qobjectdefs.h中可以看到SIGNAL() 和SLOT()的宏定义:

[cpp]  view plain   copy
  1. #ifndef QT_NO_DEBUG  
  2. # define QLOCATION "\0"__FILE__":"QTOSTRING(__LINE__)  
  3. # define METHOD(a)   qFlagLocation("0"#a QLOCATION)  
  4. # define SLOT(a)     qFlagLocation("1"#a QLOCATION)  
  5. # define SIGNAL(a)   qFlagLocation("2"#a QLOCATION)  
  6. #else  
  7. # define METHOD(a)   "0"#a  
  8. # define SLOT(a)     "1"#a  
  9. # define SIGNAL(a)   "2"#a  
  10. #endif  

所以这两个宏的作用就是把函数名转换为字符串并且在前面加上标识符。

比如:SIGNAL(read())展开后就是"2read()";同理SLOT(read())展开后就是"1read()"。

[cpp]  view plain   copy
  1. connect(sender,SIGNAL(signal()),receiver,SLOT(slot()));  
  2. 实际上就是connect(sender,“2signal()”,receiver,“1slot())”;  

搞明白了实际的参数就可以来看connect的真正实现过程了,在QObject.cpp文件中可以找到connect的实现代码。

[cpp]  view plain   copy
  1. bool QObject::connect(const QObject *sender, const char *signal,  
  2.                       const QObject *receiver, const char *method,  
  3.                       Qt::ConnectionType type)  
  4. {  
  5.     {  
  6.         const void *cbdata[] = { sender, signal, receiver, method, &type };  
  7.         if (QInternal::activateCallbacks(QInternal::ConnectCallback, (void **) cbdata))  
  8.             return true;  
  9.     }  
  10.   
  11.     if (sender == 0 || receiver == 0 || signal == 0 || method == 0) {  
  12.         qWarning("QObject::connect: Cannot connect %s::%s to %s::%s",  
  13.                  sender ? sender->metaObject()->className() : "(null)",  
  14.                  (signal && *signal) ? signal+1 : "(null)",  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值