我有一个包含两个线程的简单程序:
QApplication::execboost::asio::io_serviceTCP事件(例如连接或接收数据)会导致GUI发生更改。通常,它们setText在QLabel上并隐藏各种小部件。当前,我正在TCP客户端线程中执行这些操作,这似乎很不安全。
如何正确地将事件发布到Qt主线程?我正在寻找的Qt变体boost::asio::io_service::strand::post,将事件发布到boost::asio::io_service事件循环。
在我的(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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Read_DPC()返回我想要发送到GUI中的lineEdit的int值.
主要类看起来像
class DPC: public QThread
{
Q_OBJECT
public:
void run();
signals:
void currentCount(int);
};
Run Code Online (Sandbox Code Playgroud)
此代码在main函数中调用为:
DPC *newDPC = new DPC;
connect(newDPC, SIGNAL(currentCount(int)), SLOT(oncurrentCount(int)));
connect(newDPC, SIGNAL(finished()), newDPC, SLOT(deleteLater()));
newDPC->run();
Run Code Online (Sandbox Code Playgroud)
如何防止此代码冻结我的GUI?我究竟做错了什么?谢谢!