QObject成员函数connect()函数

本文详细解析了QObject::connect函数的使用规则,包括连接的类必须继承自QObject,信号和槽函数需指定参数类型,信号与槽的匹配原理,连接类型的选取以及参数传递的注意事项。同时,介绍了不同连接方式对效率和数据安全性的影响,并提供了多种connect函数的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值