您的位置:首页 > 编程语言 > Qt开发

Qt信号和槽的个人总结

2015-10-16 19:22 405 查看
1、connect

[cpp]viewplaincopy

connect(sender,SIGNAL(signal()),receiver,SLOT(slot()));

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

[cpp]viewplaincopy

#ifndefQT_NO_DEBUG

#defineQLOCATION"\0"__FILE__":"QTOSTRING(__LINE__)

#defineMETHOD(a)qFlagLocation("0"#aQLOCATION)

#defineSLOT(a)qFlagLocation("1"#aQLOCATION)

#defineSIGNAL(a)qFlagLocation("2"#aQLOCATION)

#else

#defineMETHOD(a)"0"#a

#defineSLOT(a)"1"#a

#defineSIGNAL(a)"2"#a

#endif

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

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

[cpp]viewplaincopy

connect(sender,SIGNAL(signal()),receiver,SLOT(slot()));

实际上就是connect(sender,“2signal()”,receiver,“1slot())”;

2、slots,signals

Qt4源码定义的宏如下:

#defineslots

#definesignalsprotected

#defineemit

再来看例子:

#ifndefCOUNTER_H

#defineCOUNTER_H


#include<QObject>


classCounter:publicQObject

{

Q_OBJECT


public:

Counter();


private:

intm_value1;

intm_value2;


publicslots:

voidsetValue1(intvalue);

voidsetValue2(intvalue);


signals:

voidvalueChanged1(intnewValue);

voidvalueChanged2(intnewValue);

};


#endif//COUNTER_H


注意,头文件定义的publicslots和signals对C++编译器而言没有意义,会被替换成public和protected。他们的真实意图其实是给moc工具使用的,moc根据这些字符串关键字匹配,用来生成文件moc_Counter.cpp。Qt源码的构建过程是先moc转换然后再执行C++编译器。moc的目的是展开信号和槽,生成一个能让编译器读懂的源文件。

以下是生成的moc文件:

QT_BEGIN_MOC_NAMESPACEstaticconstuintqt_meta_data_Counter[]={

//content:6,//revision//指明moc生成代码的版本号:Qt4的moc生成的代码,该值是6,也就是相当于mocv6;Qt5则是70,//classname//类名的索引,在数组qt_meta_stringdata_Counter的起始下标是00,0,//classinfo4,14,//methods//有4个函数(2个信号函数,2个槽函数);函数的描述在数组qt_meta_data_Counter的起始下标是140,0,//properties0,0,//enums/sets0,0,//constructors0,//flags2,//signalCount//信号函数的数量

//signals:signature,parameters,type,tag,flags18,9,8,8,0x05,//信号的索引,在数组qt_meta_stringdata_Counter的起始下标是18,flags:0x05表示是信号37,9,8,8,0x05,//同上

//slots:signature,parameters,type,tag,flags62,56,8,8,0x0a,//槽的索引,在数组qt_meta_stringdata_Counter的起始下标是62,flags:0x0a表示是槽

77,56,8,8,0x0a,//同上

0//eod};

staticconstcharqt_meta_stringdata_Counter[]={"Counter\0\0newValue\0valueChanged1(int)\0""valueChanged2(int)\0value\0setValue1(int)\0""setValue2(int)\0"};

文章来源:

http://blog.csdn.net/oowgsoo/article/details/1529411Qt源码分析之信号和槽机制

http://www.devbean.net/2012/12/how-qt-signals-and-slots-work/Qt信号槽的实现

http://woboq.com/blog/how-qt-signals-slots-work.htmlHowQtSignalsandSlotsWork

http://mobile.51cto.com/symbian-270982_all.htm详解QT源码之QT元对象系统和信号槽机制

http://mobile.51cto.com/symbian-288016.htm解析关于QtQuick宏学习教程
http://blog.csdn.net/superfpe/article/details/5782707Qt的Signal和Slot机制(一)★

http://blog.csdn.net/superfpe/article/details/5788636Qt的Signal和Slot机制(二)★

http://blog.csdn.net/ybjx111/article/details/8272405QTQObject::connect函数的学习★
http://blog.csdn.net/libaineu2004/article/details/19476039
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: