unexplained delay after QProgressBar finish loading

后端 未结 2 904
渐次进展
渐次进展 2021-01-24 10:47

I have emit signal from a loop (which make some calculations) that triggers progress bar update which located on the main GUI, after the loop ends the progress bar updated to 10

2条回答
  •  心在旅途
    2021-01-24 11:28

    In your code sample, there is actually only one thread. When on_btn_nextProcess_clicked() is called, it shows the progress bar, then runs processMethod() in the same thread. Ideally you want to separate your UI and Data Processing logic.

    In intialization, create a separate QThread, start it, and move your LogicClass object to that thread by calling logicClassObject->moveToThread([your new thread]). Then, turn processMethod() into a slot, create a startProcessing() signal in MainWindow and connect the two. Finally, create a processingDone() slot in MainWindow and a finishedProcessing() slot in LogicClass and connect them. When this is all set up you can change your code to the following:

    void LogicClass::processMethod(...)
    {
        Loop(...)
        {
            emit processBarSignal(value);
            ...some calculations...
        }
        emit processingDone();
    }
    
    void MainWindow::on_btn_nextProcess_clicked()
    {
        m_ui->pBar_process->setVisible(true);
        emit startProcessing(...);
    }
    
    void MainWindow::finishedProcessing()
    {
        m_ui->pBar_process->setVisible(false);
    }
    

    Whenever you connect signals and slots from two separate threads, multithreading is taken care of automatically. Emitting the signal in one thread causes an event to be qeued in the other which only calls the slot once the second thread regains control.

    In this case, the UI thread will schedule an event in the processing thread to start processing. The processing thread will then continually schedule progressBar value updates and finally schedule an event to turn off the progress bar when its done. The two threads will run according to the OS thread scheduler and processing won't block UI.

提交回复
热议问题