关于对qt connect函数的理解

来源:互联网 发布:windows10怎么隐藏软件 编辑:程序博客网 时间:2024/06/08 08:37

connect,是QT中的连接函数,将信号发送者sender对象中的信号signal与接受者receiver中的member槽函数联系起来。

关于cnnnect 函数的实用

首先要链接的两个类必须继承与QObject,同时添加 Q_OBJECT;

在qt中QObject::connect中填写的signal和slot函数,一定要填写参数类型;

因为类中的函数可以,也就是,重载函数名一样,参数不一样,如果QObject::connect中的函数没有参数类型,则无法正确连接;

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)));

在参数部分,如定义了:typedef unsigned char BYTE;

//signal:

void CClass1::setBuf( BYTE * );

//pulic slots:

void CClass2::setBuf( unsigned char * )

{

MessageBoxQ( "消息响应" );

}

这样,通常可以用BYTE替换unsigned char ;

但是在QObject::connect( pClass1, SIGNAL( setBuf( BYTE * ) ), pClass2, SLOT( setBuf( unsigned char * ) ) );

编译时不会有问题的,但是消息无法响应,

修改方法:

void CClass2::setBuf( unsigned char * ) 为 void CClass2::setBuf( BYTE* )

QObject::connect( pClass1, SIGNAL( setBuf( BYTE * ) ), pClass2, SLOT( setBuf( BYTE * ) ) );

可能错误的原因:

SIGNAL 和 SLOT是将其内容转为字符串,

所以,如果消息传递前 函数和参数 是按照字符串严格比较话,那么 “BYTE” 和“unsigned char” 就不同了;

原创粉丝点击