1:首先要链接的两个类必须继承于QObject,同时添加 Q_OBJECT。
2:在qt中QObject::connect中填写的signal和slot函数,一定要填写参数类型。
因为类中的函数可以,也就是,重载函数名一样,参数不一样,如果QObject::connect中的函数没有参数类型,则无法正确连接。
3:QObject::connect中的signal 和 slot 函数一定要有参数类型, 但是,不可以有参数:
You must use the SIGNAL() and SLOT() macros when specifying the signal and the method, for example:
QLabel *label = new QLabel;
QScrollBar *scrollBar = new QScrollBar;
QObject::connect(scrollBar, SIGNAL(valueChanged(int)), label, SLOT(setNum(int)));
This example ensures that the label always displays the current scroll bar value. Note that the signal and slots parameters must not contain any variable names, only the type. E.g. the following would not work and return false:
// WRONG -- 必须有参数类型,但是不能有变量名
QObject::connect(scrollBar, SIGNAL(valueChanged(int value)), label, SLOT(setNum(int value)));
4:在参数部分,如果定义了:
typedef unsigned char BYTE;
//signal:
void Class1::setBuf( BYTE * );
//pulic slots:
void Class2::setBuf( unsigned char * )
{
MessageBoxQ( "消息响应" );
}
这样,通常可以用BYTE替换unsigned char ;
但是在
QObject::connect( pClass1, SIGNAL(setBuf(BYTE *)), pClass2, SLOT(setBuf(unsigned char *)));
编译时不会有问题的,但是消息无法响应。
修改方法:
将void Class2::setBuf( unsigned char *) 修改为 void Class2::setBuf( BYTE *)
QObject::connect( pClass1, SIGNAL(setBuf(BYTE *)), pClass2, SLOT(setBuf(BYTE *)));
可能错误的原因:
SIGNAL 和 SLOT是将其内容转为字符串,所以,如果消息传递前 函数和参数 是按照字符串严格比较话,那么 “BYTE” 和“unsigned char” 就不同了。具体原因需要分析源码。
5:关于 QObject::connect 函数声明:
QMetaObject::Connectionconnect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection);
从这里可以看出: 最后一个参数是设置连接类型,默认参数是Qt::AutoConnection;
Qt::ConnectionType描述:
enum Qt::ConnectionType
This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.
Constant Value Descrip