本文介绍了QProgressBar没有显示进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更新更新进度条的第一个天真之处是在循环中包含以下行,这些行在进行处理,如下所示:

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(data.hasMoreItems())
{
    doSomeProcessing(data.nextItem())

    //Added these lines but they don't do anything
    ui->progressBar->setValue(numberProcessed++);
    ui->progressBar->repaint();
}

我认为添加repaint()会在更新GUI时使执行暂停,但是显然不是那么简单.看完问题后:

I thought adding the repaint() would make the execution pause while it updated the GUI, but apparently it's not that simple. After looking at the questions:

QProgressBar错误
进度栏未显示进度

看来我将不得不把数据处理放在另一个线程中,然后将来自数据处理线程的信号连接到GUI线程以更新进度条.我对GUI和线程缺乏经验,我想知道是否有人可以将我指向正确的方向,即,我应该在此使用哪些Qt类.我猜想我需要一个QThread对象,但是我一直在浏览QProgressBar文档,但是它没有提到线程主题.

it looks like I'm going to have to put the data processing in a different thread and then connect a signal from the data processing thread to the GUI thread to update the progressbar. I'm rather inexperienced with GUIs and threads and I was wondering if anyone could just point me in the right direction, ie what Qt classes should I be looking at using for this. I'd guess I need a QThread object but I've been looking through the QProgressBar documentation but it doesn't bring up the topic of threading.

推荐答案

正如@rjh和@Georg所指出的,本质上有两种不同的选择:

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

  1. 使用 QApplication :: processEvents()强制处理事件或
  2. 创建一个线程,该线程发出的信号可用于更新进度栏
  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.

了解线程最重要的事情是,除了主GUI线程(既不启动也不创建)之外,您永远无法直接从线程内部更新GUI .

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.

QObject :: connect()是 Qt :: ConnectionType 枚举,默认情况下考虑是否涉及线程.

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

因此,您应该能够创建一个简单的QThread子类来进行处理:

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());
    }
 }

然后在您的GUI代码中的某处:

And then somewhere in your GUI code:

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

这篇关于QProgressBar没有显示进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:02