赞
踩
有监听线程A和传输线程B,在线程A中开启监听并通过incomingConnection
方法得到native socket句柄,然后通过信号槽传递给线程B,以实现B线程中创建QTcpSocket对象。但线程B中的槽一直不响应。
class TcpServer : public QTcpServer { Q_OBJECT public: explicit TcpServer(QObject *parent = 0); signals: void newConnection(qintptr socketDescriptor); protected: virtual void incomingConnection(qintptr socketDescriptor) { emit newConnection(socketDescriptor); } }; class ListenWorker : public QObject { ... public slots: void on_startListen(const QString &ip, int port) { server = new TcpServer ; connect(server, &TcpServerMT::newConnection, this, [=](qintptr desc) { emit sig_NewConnected(desc); //该槽得到响应 }); server->listen(QHostAddress(ip), port); } signals: sig_newConnection(qintptr desc); private: TcpServer *server; } ... class TransmitWorker : public QObject { ... public slots: on_newConnection(qintptr desc){ ... } //该槽无法得到响应 } ... void main() { ... QThread *threadA = new QThread; ListenWorker *workerA = new ListenWorker; workerA->moveToThread(threadA); QThread *threadB = new QThread; TransmitWorker*workerB = new TransmitWorker; workerB->moveToThread(threadB); connnect(workerA, &ListenWorker::sig_newConnection, workerB, &TransmitWorker::on_newConnection); workerA->start(); workerB->start(); ... }
位于线程A同线程下的槽没问题,而线程B的槽则报错
QObject::connect: Cannot queue arguments of type ‘qintptr’ (Make sure ‘qintptr’ is registered using qRegisterMetaType().)
将ListenWorker::sig_newConnection
和TransmitWorker::on_newConnection
的形参类型改为quint64
则可
Qt规定,只要信号槽的连接方式为Queue,就要事先告诉元对象参数类型,通过qRegisterMetaType
https://doc.qt.io/qt-5/qobject.html#connect
https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。