QT 重写run函数实现多线程,槽函数在哪里执行

QT 重写run函数实现多线程 ,各部分执行线程测试

1、tcprecv 为继承QThread的子类TcpThread的对象,在mainwindow构造函数中被声明

2、在TcpThread类中声明

QTcpSocket *tcpSocket;                  //与下位机通讯套接字

3、构造函数中

tcpSocket = new QTcpSocket(); 
connect(tcpSocket,SIGNAL(connected()),this,SLOT(printConnectREsult()));

4、在run中使用

tcpSocket->connectToHost(ip,port);

报错:

2019-05-17 10:35:16 :QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTcpSocket(0x1ce2fe62b30), parent’s thread is QThread(0x1ce26d75d80), current thread is TcpThread(0x1ce28da3c30)

debug输出结果:

2019-05-17 10:35:16 :tcprecv gouzao QThread(0x1ce26d75d80) this TcpThread(0x1ce28da3c30)  //this 指向和currentThread返回不一样
2019-05-17 10:35:16 :main thread QThread(0x1ce26d75d80)

2019-05-17 10:35:16 :tcprecv slot QThread(0x1ce26d75d80) this TcpThread(0x1ce28da3c30) //this 指向和currentThread返回不一样
2019-05-17 10:35:16 :tcprecv run TcpThread(0x1ce28da3c30) this TcpThread(0x1ce28da3c30)

总结:

1、QThread子类对象的构造函数、槽函数、均在主线程中执行

2、在子类构造函数中调用currentThread,返回了主线程ID

3、在构造函数 和 run函数中调用this 指向一致,都为子线程

尝试方案:

1、构造函数中加this

tcpSocket = new QTcpSocket(this);  //报错跟上面一致,构造中加不加this都报错

2、将QTcpSocket的构造放到run函数

在run函数中 

tcpSocket = new QTcpSocket();  //不能加this,加了会报错
connect(tcpSocket,SIGNAL(connected()),this,SLOT(printConnectREsult()));  //不再报parent错误,槽函数也是在主线程执行

3、最终

在run函数中 

QTcpSocket *tcpSocket = new QTcpSocket();

connect(tcpSocket,SIGNAL(connected()),this,SLOT(printConnectREsult()));//不再报parent错误,槽函数也是在主线程执行

所以还是推荐大家用 movetothread,而不是写QThread子类,避免一些麻烦

https://www.zhihu.com/answer/130770474

    原文作者:清凉简装
    原文地址: https://blog.csdn.net/qq_20515461/article/details/90291128
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞