QProgressBar not showing progress?

后端 未结 3 624
耶瑟儿~
耶瑟儿~ 2020-12-01 22:07

My first naive at updating my progress bar was to include the following lines in my loop which is doing the processing, making something like this:

while(dat         


        
3条回答
  •  一生所求
    2020-12-01 22:34

    As @rjh and @Georg have pointed out, there are essentially two different options:

    1. Force processing of events using QApplication::processEvents(), OR
    2. Create a thread that emits signals that can be used to update the progress bar

    If you're doing any non-trivial processing, I'd recommend moving the processing to a thread.

    The most important thing to know about threads is that except for the main GUI thread (which you don't start nor create), you can never update the GUI directly from within a thread.

    The last parameter of QObject::connect() is a Qt::ConnectionType enum that by default takes into consideration whether threads are involved.

    Thus, you should be able to create a simple subclass of QThread that does the processing:

    class DataProcessingThread : public QThread
     {
    
     public:
         void run();
     signals:
         void percentageComplete(int);
     };
    
     void MyThread::run()
     {
        while(data.hasMoreItems())
        {
          doSomeProcessing(data.nextItem())
          emit percentageCompleted(computePercentageCompleted());
        }
     }
    

    And then somewhere in your GUI code:

    DataProcessingThread dataProcessor(/*data*/);
    connect(dataProcessor, SIGNAL(percentageCompleted(int)), progressBar, SLOT(setValue(int));
    dataProcessor.start();
    

提交回复
热议问题