簡體   English   中英

QT錯誤中的C ++線程關聯

[英]C++ thread affinity in QT error

我有一個簡單的Qt應用程序,可以將文件從文件夾發送到服務器。

如果沒有Internet連接,則預期的行為是將文件保存以供以后在“脫機”文件夾中使用。 然后,幾分鍾后,應用程序本身(在另一個線程中)將不得不檢查該文件夾,以查看是否有等待發送的文件。

這是一些代碼,我去除了一些不必要的行:

main.cpp中:

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

    MainWin win;
    win.show();

    return app.exec();
}

mainwin.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();


}

harvester.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線程與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!
}

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM