問題描述
我在 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:無法為不同線程中的父級創建子級的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!