QObject:无法为不同线程中的父级创建子级

时间:2023-01-02
本文介绍了QObject:无法为不同线程中的父级创建子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 Windows 7 Ultimate 下使用 Qt 4.6.0(32 位).考虑以下 QThread:

I am using Qt 4.6.0 (32 bit) under Windows 7 Ultimate. Consider the following QThread:

class ResultThread : public QThread
{
Q_OBJECT

    QString _post_data;
    QNetworkAccessManager _net_acc_mgr;

signals:
    void onFinished(QNetworkReply* net_reply);

private slots:
    void onReplyFinished(QNetworkReply* net_reply);

public:
    ResultThread();

    void run();
    void setPostData(const QString& post_data);
};

实施

ResultThread::ResultThread() : _net_acc_mgr(this)
{
    connect(&_net_acc_mgr, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(onReplyFinished(QNetworkReply*)));
}

void ResultThread::onReplyFinished(QNetworkReply* net_reply)
{
    emit onFinished(net_reply);
}

void ResultThread::setPostData(const QString& post_data)
{
    _post_data = post_data;
}

void ResultThread::run()
{
    _net_acc_mgr.post(QNetworkRequest(QUrl("http://[omitted]")),
                      QByteArray(_post_data.toStdString().c_str()));
}

每当 _net_acc_mgr.post()ResultThread::run() 中执行时,我在 Qt Creator 中得到以下应用程序输出:

Whenever _net_acc_mgr.post() is executed in ResultThread::run(), I got the following Application Output in Qt Creator:

QObject:无法为不同线程中的父对象创建子对象.

QObject: Cannot create children for a parent that is in a different thread.

(父为QNetworkAccessManager(0x22fe58),父线程为QThread(0x9284190),当前线程为ResultThread(0x22fe48)

(Parent is QNetworkAccessManager(0x22fe58), parent's thread is QThread(0x9284190), current thread is ResultThread(0x22fe48)

这是什么意思?如何解决?

What does this mean? How to solve it?

推荐答案

run() 成员函数在不同的线程中执行,而不是 QNetworkRequestManager 所在的线程对象已创建.

The run() member function is executed in a different thread, rather than the thread where QNetworkRequestManager object was created.

当您使用多线程时,Qt 总是会发生这种不同线程的问题.解决这个问题的规范方法是使用信号.

This kind of different-thread problems happen all the time with Qt when you use multiple threads. The canonical way to solve this problem is to use signals and slots.

QNetworkRequestManager所属的对象中创建一个,在ResultThread中创建一个信号并连接两者在某处,ResultThread 的构造函数将是一个好地方.

Create a slot in the object where QNetworkRequestManager belongs to, create a signal in ResultThread and connect both of the somewhere, the constructor of ResultThread would be a good place.

当前在 ResultThread::run() 中的代码进入新的,并被替换为 emit(yourSignal()).如有必要,将指向您的 ResultThread 的指针作为参数与您的发射函数一起发送,以获得对成员函数/变量的访问.

The code which is currently in ResultThread::run() goes to the new slot, and is replaced by a emit(yourSignal()). If necessary send a pointer to your ResultThread as a parameter with your emit function to gain access to member functions/variables.

这篇关于QObject:无法为不同线程中的父级创建子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!