![](/img/trans.png)
[英]QNetworkAccessManager freezes GUI even when in another thread
[英]Launching a while-loop freezes program even if using another thread
在我的(Qt-)程序中,我需要一個連續的值請求,該值是從外部來源獲得的。 但是我不希望該請求凍結整個程序,所以我為此函數創建了一個單獨的線程。 但是,即使它在單獨的線程中運行,GUI也會凍結。 為什么?
請求功能的代碼:
void DPC::run()
{
int counts = 0, old_counts = 0;
while(1)
{
usleep(50000);
counts = Read_DPC();
if(counts != old_counts)
{
emit currentCount(counts);
old_counts = counts;
}
}
}
Read_DPC()
返回一個我要發送到GUI中的lineEdit的int值。
主班看起來像
class DPC: public QThread
{
Q_OBJECT
public:
void run();
signals:
void currentCount(int);
};
該代碼在主要功能中的調用方式為:
DPC *newDPC = new DPC;
connect(newDPC, SIGNAL(currentCount(int)), SLOT(oncurrentCount(int)));
connect(newDPC, SIGNAL(finished()), newDPC, SLOT(deleteLater()));
newDPC->run();
如何防止此代碼凍結GUI? 我究竟做錯了什么? 謝謝!
似乎您在GUI線程中運行代碼是因為您使用run()
方法來啟動線程,因此請嘗試按文檔和許多示例所述調用start()
。
嘗試:
DPC *newDPC = new DPC;
connect(newDPC, SIGNAL(currentCount(int)), SLOT(oncurrentCount(int)));
connect(newDPC, SIGNAL(finished()), newDPC, SLOT(deleteLater()));
newDPC->start();//not run
無論如何,您都可以調用thread()
方法或currentThread()來查看某些對象位於哪個線程中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.