John Doe
John Doe

Reputation: 1869

QProgressBar busy not working

I am trying to create a QProgressBar to indicate the execution of an action of which I don't know the time it will take to complete before execution.

Right now I have the following

QProgressBar DLbar;
DLbar.setMaximum(0);
DLbar.setMinimum(0);
DLbar.show();

I have set the minimum and maximum both to 0, which should result in a busy indicator based on the Qt documentation:

If minimum and maximum both are set to 0, the bar shows a busy indicator instead of a percentage of steps. This is useful, for example, when using QNetworkAccessManager to download items when they are unable to determine the size of the item being downloaded.

When I run the program the progress bar is shown but instead of having the busy indicator it's full and stays like that until the operation finishes.

I tried setting the DLbar parent to be the main window but there's the same problem.

Example:

QProgressBar DLbar;
DLbar.setMaximum(0);
DLbar.setMinimum(0);
DLbar.show();
for( int i=0; i<1000000; i++ )
    qDebug() << i;

Upvotes: 3

Views: 1412

Answers (1)

G.M.
G.M.

Reputation: 12889

The basic problem is that you're not allowing the Qt event loop to process events. A minimal example to demonstrate would be something like...

#include <cstdlib>
#include <chrono>
#include <thread>
#include <QApplication>
#include <QProgressBar>

int
main (int argc, char **argv)
{
  QApplication app(argc, argv);
  QProgressBar DLbar;
  DLbar.setMaximum(0);
  DLbar.setMinimum(0);
  DLbar.show();

  /*
   * The following sleep will prevent any events being processed for 10s...
   */
  std::this_thread::sleep_for(std::chrono::seconds(10));

  /*
   * ...after which we start the event loop and everything should start working.
   */
  exit(app.exec());
}

If you're going to be using Qt you really need to get a firm understanding of the underlying event system.

Edit 1: You ask...

i still don't understand why it's not working even if i use QCoreApplication::processEvents() inside the loop.

It will work if, in the example above, you replace...

exit(app.exec());

with...

while (true)
  QCoreApplication::processEvents();

Upvotes: 2

Related Questions