gpt4 book ai didi

QT 错误中的 C++ 线程关联

转载 作者:行者123 更新时间:2023-11-30 04:15:13 35 4
gpt4 key购买 nike

我有一个简单的 Qt 应用程序,可以将文件从文件夹发送到服务器。

当没有互联网连接时,预期的行为是将文件保存在“离线”文件夹中以备后用。然后,每隔几分钟,应用程序本身(在不同的线程中)将不得不检查该文件夹以查看是否有一些文件正在等待发送。

这是一些代码,我删除了一些不必要的行:

主要.cpp:

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

MainWin win;
win.show();

return app.exec();
}

主窗口.cpp:

MainWin::MainWin(QWidget * parent) : QWebView(parent)
{

m_network = new QNetworkAccessManager(this);

m_communicationHandler = new TestNetwork(this, m_network);

// harvie
Harvester * harvie = new Harvester(m_network);
harvie->start();


}

收割机.cpp:

标题:

class Harvester : public QThread
{
Q_OBJECT
public:
QNetworkAccessManager * m_network;
Harvester(QNetworkAccessManager * m_network);
...
}

来源:

Harvester::Harvester(QNetworkAccessManager * m)
{
qDebug() << "harvie start" << endl;
this->m_network = m;
}

...

bool Harvester::sendFile(QFileInfo *fileInfo) {

connect(this->m_network,SIGNAL(finished(QNetworkReply*)),this,SLOT(validateReply(QNetworkReply*)));

QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

QHttpPart filePart;
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/xml")); // @todo test
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"someFile\"; filename=\"" + fileInfo->baseName() + ".xml\""));

QFile *file = new QFile(fileInfo->filePath());
file->open(QIODevice::ReadOnly);
filePart.setBodyDevice(file);
file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart


multiPart->append(filePart);

qDebug() << "post" << endl;

QNetworkReply *reply = this->m_network->post(QNetworkRequest(QUrl("XXX")), multiPart);

multiPart->setParent(reply); // delete the multiPart with the reply

return true;
}

这是我收到的错误:

Warning: QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNetworkAccessManager(0x3e46c30), parent's thread is QThread(0x3dd6d50), current thread is Harvester(0x3e47eb8)

我猜 QNetworkAccessManager 在尝试从另一个线程发送请求时发生冲突,即使我使用相同的指针也是如此。

我还没有尝试过的另一个解决方案是将收割机作为一个单独的进程运行,但首先我想通过线程来解决它。

谢谢

最佳答案

qt thread with movetothread

http://crpppc19.epfl.ch/doc/qt4-doc-html/html/qthread.html#details

http://crpppc19.epfl.ch/doc/qt4-doc-html/html/qobject.html#moveToThread

试试这个:

Harvester::Harvester(QNetworkAccessManager * m)
{
qDebug() << "harvie start" << endl;
this->m_network = m;

m_network->moveToThread(this); // Change thread affinity!
}

希望对您有所帮助。

关于QT 错误中的 C++ 线程关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452455/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com