我正在尝试创建一个“响应式图形用户界面”,这基本上意味着我有一个应用程序,并且在主窗口上有一个按钮。按下此按钮后,我希望显示“进度条窗口”,它将显示正在完成的工作的进度,当然这项工作是在单独的线程中完成的。
不幸的是,我在这个 progress_bar 窗口的 ctor 中启动一个新线程的方法似乎不起作用,我得到了卡住的 gui。 这是该项目的链接,因此您无需复制和粘贴任何内容即可下载并运行它:http://www.mediafire.com/?w9b2eilc7t4yux0
谁能告诉我我做错了什么以及如何解决它?
编辑
progress_dialog::progress_dialog(QWidget *parent) :
QDialog(parent)
{/*this is this progress dialog which is displayed from main window*/
setupUi(this);
working_thread_ = new Threaded;
connect(working_thread_,SIGNAL(counter_value(int)),progressBar,SLOT(setValue(int)),Qt::QueuedConnection);
working_thread_->start();//HERE I'M STARTING THIS THREAD
}
/*this is run fnc from the threaded class*/
void Threaded::run()
{
unsigned counter = 0;
while(true)
{
emit counter_value(counter);
counter = counter + 1 % 1000000;
}
}
最佳答案
独立于紧密循环不好的事实,您应该限制对主 GUI 线程进行更改的速率:来自线程的信号在主线程事件循环中发出后立即排队,并且作为GUI 无法快速更新,重绘事件排队而不是实时执行,这会卡住 GUI。
无论如何更新 GUI 的速度超过屏幕刷新率是没有用的。
你可以尝试这样的事情:
void Threaded::run()
{
QTime time;
time.start();
unsigned counter = 0;
// initial update
emit counter_value(counter);
while(true)
{
counter = (counter + 1) % 1000000;
// 17 ms => ~ 60 fps
if(time.elapsed() > 17) {
emit counter_value(counter);
time.restart();
}
}
}
关于c++ - 尝试启动新线程时设置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9911530/