Visual Studio 2017运行Qt代码报跨线程创建子对象错误 Qt Creator正常
问题原因及解决方案
1. 首先修正代码明显错误
你粘贴的mytcpsocket.cpp内容完全是头文件的重复定义,这是核心错误之一。如果你的实际项目中该文件内容确实如此,VS编译时不会生成正确的类实现逻辑,会导致Qt元对象系统异常,进而误判对象的线程亲和性,触发跨线程创建子对象的报错。Qt Creator的qmake执行逻辑和VS的Qt插件逻辑不同,对这类错误代码的兼容度更高,所以不会触发运行时报错。
正确的mytcpsocket.cpp实现参考如下:
#include "mytcpsocket.h" MyTcpSocket::MyTcpSocket(QObject *parent) : QObject(parent) { } MyTcpSocket::~MyTcpSocket() { socket->close(); delete socket; } void MyTcpSocket::doConnect() { socket = new QTcpSocket(this); connect(socket, &QTcpSocket::connected, this, &MyTcpSocket::connected); connect(socket, &QTcpSocket::disconnected, this, &MyTcpSocket::disconnected); connect(socket, &QTcpSocket::bytesWritten, this, &MyTcpSocket::bytesWritten); connect(socket, &QTcpSocket::readyRead, this, &MyTcpSocket::readyRead); qDebug() << "connecting..."; socket->connectToHost("bogotobogo.com", 80); if(!socket->waitForConnected(3000)) { qDebug() << "Connection error: " << socket->errorString(); } } void MyTcpSocket::connected() { qDebug() << "connected successfully"; socket->write("HEAD / HTTP/1.0\r\n\r\n"); } void MyTcpSocket::disconnected() { qDebug() << "disconnected from host"; } void MyTcpSocket::bytesWritten(qint64 bytes) { qDebug() << bytes << " bytes written"; } void MyTcpSocket::readyRead() { qDebug() << "received response:"; qDebug() << socket->readAll(); }
2. 检查VS项目Qt配置
- 确认项目已添加Network模块依赖:右键项目→属性→Qt Project Settings→Qt Modules,勾选
Network选项。 - 确认VS关联的Qt版本为5.9.9 MSVC2017版,没有混用MinGW或其他版本的Qt库。
- 清理全部编译缓存:删除项目目录下的
GeneratedFiles、Debug、Release文件夹,右键项目执行qmake后重新编译运行。
3. 兼容规避方案
如果修正后仍报错,可临时移除QTcpSocket的父对象绑定,手动管理生命周期验证问题:
将报错行socket = new QTcpSocket(this);修改为socket = new QTcpSocket();,已经在上面的示例代码中补充了手动释放socket的析构函数逻辑,可直接复用。修改后如果不再报错,说明你安装的Qt VS Tools插件和Qt 5.9.9存在兼容问题,建议更换匹配Qt 5.9.9版本的VS插件重新配置项目。
内容的提问来源于stack exchange,提问作者msaint
相关产品推荐
相关产品推荐

