尝试启动新线程时,某些设置不正确

Something is incorrectly set when try to start new thread

本文关键字:不正确 设置 线程 启动 新线程      更新时间:2023-10-16

我正在尝试创建一个"响应gui",这基本上意味着我有一个应用程序,在主窗口上有一个按钮。按下这个按钮后,我希望显示"进度条窗口",它将显示正在完成的工作的进度,当然,这项工作是在单独的线程中完成的。

不幸的是,我在这个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();            
        }
    }
}

是否尝试使用父对象启动线程?