gpt4 book ai didi

c++ - 在另一个线程中创建 QNetworkAccessManager

转载 作者:行者123 更新时间:2023-11-30 02:19:38 34 4
gpt4 key购买 nike

我在另一个线程中创建了一个 QNetworkAccessManager。该网络只能在 MyMegaThread 中使用。
QNetworkAccessManager 是从线程的 run 方法创建的:

mp_manager.reset(new QNetworkAccessManager{this});

创建时,我在控制台中收到这样的消息:

QObject: Cannot create children for a parent that is in a different thread.
(Parent is MyMegaThread(0x237eabd0ee0), parent's thread is QThread(0x237e70742a0), current thread is MyMegaThread(0x237eabd0ee0)

这个消息是完全无害的,但我想知道经理应该有哪个 parent 。
我怀疑这是因为 MyMegaThread 实例是在主线程中创建的,但我需要一个在 MyMegaThread 中创建的父实例。

执行此操作的惯用方法是什么?

最佳答案

Parent is MyMegaThread(0x237eabd0ee0), parent's thread is QThread(0x237e70742a0), current thread is MyMegaThread(0x237eabd0ee0)

此问题与 QNetworkAccessManager 无关。

这是重现警告的演示。

#include <QDebug>
#include <QThread>

class MyMegaThread : public QThread
{
Q_OBJECT
public:
using QThread::QThread;

protected:
void run() override {
qDebug()<<QThread::currentThread()<<this->thread();
new QObject(this);
}
};

// main
MyMegaThread m;
m.start();

输出:

MyMegaThread(0x60fe18) QThread(0x16a7c48)

QObject的规则:

All QObjects must live in the same thread as their parent. Consequently:

setParent() will fail if the two QObjects involved live in different threads. When a QObject is moved to another thread, all its children will be automatically moved too. moveToThread() will fail if the QObject has a parent. If QObjects are created within QThread::run(), they cannot become children of the QThread object because the QThread does not live in the thread that calls QThread::run().

http://doc.qt.io/qt-5/qobject.html#thread-affinity

必须确保运行 QThread 的代码 new QObject 与给定的父 QObject 线程相同。

mp_manager.reset(new QNetworkAccessManager{this});

关于c++ - 在另一个线程中创建 QNetworkAccessManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50632807/

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