1. 程式人生 > >QObject: Cannot create children for a parent that is in a different thread.

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

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

(Parent is QNetworkAccessManager(0x17d16c88), parent's thread is QThread(0x1643ab88), current thread is QThread(0x17d16cd8)


有可能大家在利用qt寫程式的時候遇到這類提醒,這事實上是再說父類和子類的執行緒不對。

下面是我沒解決錯誤前的程式碼

     thread_http = new QThread;
    thread_query = new QThread;
    httpA = new HttpGP;
    seriportQuery = new SeriportQuery;
 
 
    httpA->moveToThread(thread_http);
//    httpA->accessManager->moveToThread(thread_http);
    seriportQuery->moveToThread(thread_query);
 
 
    thread_http->start();
    
thread_query->start();

我線性的認為把一個類放到執行緒裡那麼相關的內部一切都放到子執行緒中了,結果就是那麼尷尬出現了上面的錯誤。


這裡指出,QNetworkAccessManager 也是一個獨立的類並不從屬HttpGP 這個類,所以它實際在工作在主執行緒,而執行完上述程式碼後HttpGP執行在子執行緒中,執行緒不匹配導致了錯誤的出現。


解決的辦法就是讓QNetworkAccessManager也移到HttpGP所在的執行緒,

httpA->accessManager->moveToThread(thread_query);//就是解決方法

例外就是在聲明後面加入(this)

    accessManager = new QNetworkAccessManager(this);

如果你在run()中實現的,那就是在run內例項化