当前位置:   article > 正文

QTcpServer::incomingConnection(qintptr)跨线程传递socket失败_make sure 'qintptr' is registered using qregisterm

make sure 'qintptr' is registered using qregistermetatype()

有监听线程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();
...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

位于线程A同线程下的槽没问题,而线程B的槽则报错

QObject::connect: Cannot queue arguments of type ‘qintptr’ (Make sure ‘qintptr’ is registered using qRegisterMetaType().)
  • 1

ListenWorker::sig_newConnectionTransmitWorker::on_newConnection的形参类型改为quint64则可

Qt规定,只要信号槽的连接方式为Queue,就要事先告诉元对象参数类型,通过qRegisterMetaType
https://doc.qt.io/qt-5/qobject.html#connect
https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/930648
推荐阅读
  

闽ICP备14008679号