Qt信号与槽传递自定义数据类型
Qt信号和槽函数只能是基于Qt的基础类型QMetaType的,比如QString、int、bool等,如果想使用自定义参数类型默认情况下是不行的会报错,查看Qt帮助文档可知在Qt信号和槽函数之间传递自定义参数时需要先使用qRegisterMetaType()注册一下
Qt帮助文档:
The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt’s meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message
QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)
call qRegisterMetaType() to register the data type before you establish the connection.
Note: This function is thread-safe.
假如自定义类型为Myclass 使用方法如下
// 在当前类的顶部添加文件引用
#include <QMetaType>
// 在构造函数中注册
qRegisterMetaType<MyClass>("Myclass");
//Myclass的引用类型需要单独注册
qRegisterMetaType<MyClass>("Myclass&");
使用qRegisterMetaType()其实就是将某种类型注册到QMetaType中去,Qt还有一个宏Q_DECLARE_METATYPE 它展开后特化后的类 QMetaTypeId ,类中的成员包含对qRegisterMetaType的调用
我们也可以使用Q_DECLARE_METATYPE声明下自定义变量,把自定义变量包装成QVarint来使用
信号和槽函数如下:
Q_SIGNALS:
void senddata(QVarint data);
private Q_SLOTS:
void senddata(QVarint data)
使用方法
//声明自定义数据类型
Q_DECLARE_METATYPE(Myclass)
//包装数据 发出信号
QVarint data
data.setValue(mydata);
emit senddata(data);
//槽函数中
void senddata(QVarint data)
{
Myclass mydata = data.value<Myclass>();
}