Forcing the Qt GUI to update before entering a separate function

前端 未结 4 1496
小蘑菇
小蘑菇 2020-12-09 02:48

This seems like it should be automatic, but apparently it\'s not. I have the following code:

    ui.my_label->setText(\"Test 1...\");
    ui.my_label->         


        
相关标签:
4条回答
  • 2020-12-09 03:23

    Defining a function...

    void YourClass::Update_Ui()
    {
    if(this->isEnabled())
        return;
    
    this->repaint();
    qApp->processEvents();
    }
    

    ...like this and make sure this is disabled (to prevent user actions) while you want to force an update of the ui was the best solution for me.

    Example how to use it inside a function (for example during a stack processing that takes lots of time):

    this->setEnabled(false);
    //Do whatever you want
    Update_Ui();
    //Do some other stuff
    this->setEnabled(true);
    

    This doesn't allow the user to disturb the processing by ui interaction (it is disabled) and updates whenever Update_Ui(); is called in the code and updates the whole ui, not just a chosen label or whatever. Note that this doesn't block signals fired by ui elements.

    0 讨论(0)
  • 2020-12-09 03:28

    You shuld be able to process the event queue before entering your code if you;

    #include <QApplication>
    

    and, when you want to refresh your GUI, call;

    qApp->processEvents();
    

    Note that it may be a good idea to let your long running process call that function now and then, to make your GUI feel more responsive.

    0 讨论(0)
  • 2020-12-09 03:31

    I just wanted to add that for me it took a combo of the two answers I saw here. So what worked for me was:

    ui.my_label->setText("Test 1...");
    ui.my_label->adjustSize();
    
    //! Both of these lines needed
    ui.my_label->repaint();
    qApp->processEvents();
    
    processThatTakesAbout30SecondsToFinish(files[0].toStdString());
    
    ui.my_label->setText("Finished.");
    ui.my_label->adjustSize();
    

    Hope this helps someone.

    0 讨论(0)
  • 2020-12-09 03:44

    If you don't care about your GUI being responsive during this time, then a call to my_label->repaint() would do the trick. Qt can't do anything automatically for you unless you yield to the event loop.

    For maximimum responsiveness you might consider running your process in a separate thread and use signal/slot connections (which are thread-safe by default) to signal to your main GUI thread when your processing is complete.

    0 讨论(0)
提交回复
热议问题