打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Qt多线程间信号槽传递非QObject类型对象的参数
Qt多线程间信号槽传递非QObject类型对象的参数
博客分类: Qt
queue argumentsqRegisterMetaType信号槽参数QtCannot queue arguments of type
一、以前就发现过这个问题:
在Qt项目中,有时候为了让自己的类,可以重载操作符 '=','<<','>>'. 也有时候需要用一个类进行文件的读写,所以很多C++类还是要简单化的,不需要继承QObject,不需要Qt的元对象机制。
但是对于这些简单C++类,有些时候要是调用Qt的信号槽当做参数进行跨线程发送,就会出现如下问题:
这种情况一般,编译可以通过,但会出现如下提示。
Cpp代码 
 
QOBject::connect:Cannot queue arguments of type 'MoSystemLog'
(Make sure 'MoSystemLog' is registed using qRegisterMetaType().)
意思是说,信号槽队列中的数据类型必须是系统能识别的元类型,不然得用qRegisterMetaType()进行注册。
二、解决方法:
第一种注册法:qRegisterMetatType<MoSystemLog>("MoSystemLog")
第二种修改Connect,加一个属性Qt::directConnection.
connect(cm, SIGNAL(sendLog(QUuid, QByteArray, bool)),
this,SLOT(sendRes(QUuid,QByteArray,bool)), Qt::DirectConnection);
三、方法解释:
1、第一种解决方法,即使用排队方式的信号-槽机制,Qt的元对象系统(meta-object system)必须知道信号传递的参数类型。这样元系统可以将信号参数COPY下来,放在队列中等待事件唤醒,供槽函数调用。Just a note here, if you would have to pass custom data types between threads in Qt. As we know, a signal-slot connection is then (by default) of type Qt::QueuedConnection. Because in such a situation Qt needs to store passed parameters for a while, it creates their temporary copies. If it doesn’t recognize the passed data type, throws out an error:
2、第二种方法,直接调用对方槽函数,不需要保存参数。但是官方认为这样做有风险。
四、背景知识:
1、首先要了解enum Qt::ConnectionType
Qt支持6种连接方式,其中3种最主要:
Qt::DirectConnection(直连方式)
当信号发出后,相应的槽函数将立即被调用。emit语句后的代码将在所有槽函数执行完毕后被执行。(信号与槽函数关系类似于函数调用,同步执行)
Qt::QueuedConnection(排队方式)
当信号发出后,排队到信号队列中,需等到接收对象所属线程的事件循环取得控制权时才取得该信号,调用相应的槽函数。emit语句后的代码将在发出信号后立即被执行,无需等待槽函数执行完毕。(此时信号被塞到信号队列里了,信号与槽函数关系类似于消息通信,异步执行)
Qt::AutoConnection(自动方式)
Qt的默认连接方式,如果信号的发出和接收这个信号的对象同属一个线程,那个工作方式与直连方式相同;否则工作方式与排队方式相同。
Qt官方文档中写明:
With queued connections, 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'
callqRegisterMetaType() to register the data type before you establish the connection.
注意上面紫色的内容。
connect的第五个参数用于指定反应速度:
若将:
connect(cm, SIGNAL(sendLog(QUuid, QByteArray, bool)),
this,SLOT(sendRes(QUuid,QByteArray,bool)));
改为:
connect(cm, SIGNAL(sendLog(QUuid, QByteArray, bool)),
this,SLOT(sendRes(QUuid,QByteArray,bool)), Qt::DirectConnection);
可解决因信号没有及时发送,致使connect的接收方的槽不能作进一步处理,但是有风险
参考文章:
1、http://blog.ayoy.net/2009/2/15/registering-custom-types
2、http://dev.wo.com.cn/bbs/redirect.jsp?fid=25127&tid=150302&goto=nextoldset
3、http://blog.csdn.net/s04023083/article/details/4746544
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
http://blog.csdn.net/qq419036154/article/deta...
QTcpSocket
QT学习小结(三)
QT的重要的概念
QT Creator 快速入门教程 读书笔记(三)
Qt之信号与槽
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服