(seemingly) simple Qt app: creating a progress bar
Page |
1 |
Hi, all –
Some of you know me already: I’ve been using Qt as an IDE for about a year now (and love it). I’ve been trying to convince a reluctant management to let me begin experimenting with putting a Qt UI on a desktop app I’m building, and now have a short window of opportunity. I think I’d like to begin with something ultra simple: our program reads a data file, processes it and produces output files. I’d like to add a progress bar to help the user monitor how far through the input file the program is.
Since my real program is way too complex to get into here, I’ve created a stub program that I think contains the essentials for this:
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- long getFileSize (fstream& f)
- {
- long end;
- f.seekg (0, ios::end);
- end = f.tellg();
- f.seekg(0, ios::beg);
- return end;
- }
- int main()
- {
- long curr, end, percent;
- string myStr;
- fstream myFile("test.pro.user");
- end = getFileSize(myFile);
- while (myFile.good())
- {
- myFile >> myStr;
- curr = myFile.tellg();
- // special handling for end of file.
- if (curr != -1)
- percent = curr * 100 / end;
- else
- percent = 100;
- cout << percent << " percent finished." << endl;
- }
- myFile.close();
- return 0;
- }
So, I’ve been doing some reading of the docs, and (as usual) I’m a little lost in how to get started. I don’t expect anyone to do this for me, but could someone point me in the right direction? I believe I want to use this:
Qt page on progress bar [developer.qt.nokia.com]
…but I’m sure there’s more to it than just including this widget.
Any guidance would be appreciated. Thanks so much.
I’ve already gotten a development team across the continent to use Qt for their IDE, so my evangelism is making (slow) progress. I think if I can pull off this, and a few embellishments, they’ll let me use Qt as the tool for the UI in an upcoming project with large commercial implications.
71 replies
I think you would be much better off if you start developing your app in Qt. Starting in std and then migrating to Qt is harder – especially when you are learning.
Standard way here would be to update progress bar using signal and slot mechanism, but that would require a big rewrite of your code. For something simpler that might (I’ve not tested) work, try this:
- #include <QApplication>
- #include <QProgressBar>
- int main()
- {
- long curr, end, percent;
- string myStr;
- fstream myFile("test.pro.user");
- end = getFileSize(myFile);
- bar.setRange(0, 100);
- bar.setValue(0);
- bar.show();
- while (myFile.good())
- {
- myFile >> myStr;
- curr = myFile.tellg();
- // special handling for end of file.
- if (curr != -1)
- percent = curr * 100 / end;
- else
- percent = 100;
- bar.setValue(persent);
- cout << percent << " percent finished." << endl;
- }
I’m not sure it will work, I would normally have done it in a much different way. For an example app, you can take a look at my sPDaR [gitorious.org], but proceed with caution, as this is a very old and crude code :) Works, though.
Be aware, that updates to the progress bar are more or less blocked as long as the while loop is running. To make the application responsible while the work is done, one could consider using a worker thread. As a workaround, one should at least run the even loop handler after changing the progress bar’s values. A QProgressDialog can be an alternative too, it suffers from a non running event loop too.
You can do this, but the event loop must be run regularly, so that the events (e.g. repaints, mouse events, key press event, and so on) are handled. As long as you are within the while loop, this is only done if you call QApplication::processEvents() manually. Otherwise the the application is blocked, on the Mac it usually shows the rotating, colored “beach ball” and on Windows that “this application doesn’t react” message.
OK, so if I can pursue this a bit further:
1. the application, once started is completely compute-bound. No action from the user is needed nor permitted.
2. in my “real” app, it executes about 750 loops per second. (I’m talking about my compute loops, not the event loops).
But, I’m left with the impression that you don’t like this idea. So, returning to the original example, what would have been a preferred design?
Thanks.
In that case I would move the actual computation to a worker thread. Use the pattern that’s recommended nowadays: Create a QObject subclass that does the work and QThread as a managing helper only (no subclassing of QThread). The Threads, Events and QObjects wiki article has the details. Your worker object defines a signal, say progress(int value, int max) that you emit, say every 200 iterations of your loop (in every iteration it would just flood the app with events!). The main thread does little less than opening a progress bar (or progress dialog) and spins the event loop for the GUI.
OK…I scanned the article you identified. I was taken by this line:
Nine times out of ten, a quick inspection of their code shows that the biggest problem is the very fact they’re using threads in the first place, and they’re falling in one of the endless pitfalls of parallel programming.
So…am I “doing this wrong?” I’ll go this route if you think it’s best, but I’m open to other suggestions (as long as they don’t entail a complete re-write of my app; the boss won’t go for that).
Back to the example I posted originally: would you (hypothetically) use threads for that as well?
In your case I would say that going with multithreaded architecture is ok. That 9-of-10 statement referes to stuff where you don’t need MT at all, like putting an already asynchronous API like QNAM or sockets into a thread to make it asynchronous.
To answer the last question: yes, I would use a thread for this.
OK, I’ve done a little work on this. I know it’s incomplete, and I’m sure it’s not right yet, but…I’m ready to ask for some feedback. Thanks…
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- #include <QApplication>
- #include <QProgressBar>
- long getFileSize (fstream& f)
- {
- long end;
- f.seekg (0, ios::end);
- end = f.tellg();
- f.seekg(0, ios::beg);
- return end;
- }
- {
- Q_OBJECT
- private:
- fstream myFile;
- public:
- WorkerThread() : myFile("test.pro.user") {}
- void run()
- {
- long curr, end, percent;
- string myStr;
- end = getFileSize(myFile);
- while (myFile.good())
- {
- myFile >> myStr;
- curr = myFile.tellg();
- // special handling for end of file.
- if (curr != -1)
- percent = curr * 100 / end;
- else
- percent = 100;
- // some kind of signal to be emitted here
- cout << percent << " percent finished." << endl;
- }
- }
- signals:
- void percentChanged(int percent);
- };
- int main(int argc, char *argv[])
- {
- WorkerThread worker;
- bar.setRange(0, 100);
- bar.setValue(0);
- bar.show();
- // bar.setValue(percent);
- return app.exec();
- }
- void WorkerThread::percentChanged(int percent) {}
On a first glance, that looks good. Despite the fact that you might consider using QFile/QTextStream for the file operations and QFileInfo for getting the file size (instead of your method).
Then you must not define the method for the signal yourself, this is done automatically by moc. It is sufficient to just declare the signal in the class header file.
The signal must be emitted in the run method of your thread:
- // some kind of signal to be emitted here
- emit percentChanged(percent);
You’ll also have to connect that signal to the progress bar:
- connect(worker, SIGNAL(percentChanged(int)), bar, SLOT(setValue(int)));
Also, the worker needs to be moved to a thread, and eventually started:
- bar.setRange(0, 100);
- bar.setValue(0);
- bar.show();
- WorkerThread worker;
- QThread thread;
- worker.moveToThread(&thread);
- // run the run method of the worker object once the thread has started
- connect(&thread, SIGNAL(started())), &worker, SLOT(run()));
- // update the progress bar
- connect(&worker, SIGNAL(percentChanged(int)), &bar, SLOT(setValue(int)));
- thread.start();
to make the autostart work, you must declare WorkerThread::run() as public slot.
On a first glance, that looks good. Despite the fact that you might consider using QFile/QTextStream for the file operations and QFileInfo for getting the file size (instead of your method)
Good to know about those…thanks. For now, I’ll just leave it as is. The plan is to:
- get this working with a minimum of effort on my sample program
- transfer the Qt-specific code to my simulator
- let the powers-that-be see how cool even a bit of Qt razzle-dazzle is
- go whole-hog on the big job that’s hopefully coming up this spring
Then you must not define the method for the signal yourself, this is done automatically by moc. It is sufficient to just declare the signal in the class header file.
Oh yeah; I knew that (sort of).
The signal must be emitted in the run method of your thread:
// some kind of signal to be emitted here emit percentChanged(percent);You’ll also have to connect that signal to the progress bar:
connect(worker, SIGNAL(percentChanged(int)), bar, SLOT(setValue(int)));Also, the worker needs to be moved to a thread, and eventually started:
bar.setRange(0, 100); bar.setValue(0); bar.show(); WorkerThread worker; QThread thread; worker.moveToThread(&thread); // run the run method of the worker object once the thread has started connect(&thread, SIGNAL(started())), &worker, SLOT(run())); // update the progress bar connect(&worker, SIGNAL(percentChanged(int)), &bar, SLOT(setValue(int))); thread.start();to make the autostart work, you must declare WorkerThread::run() as public slot.
Done, done and done. I’m geting a compiler error that “‘connect’ was not declared in this scope.” I’m including QObject; isn’t that where connect lives?
EDIT: does the connect need object context? There isn’t any in the example on the signals/slots doc page.
Oh, using QFile and friends is much more easier than the stdlib methods – give it a try! :)
I believe you, but…the goal for this exercise is not to show off all of Qt’s programming features, but to impress upon some reluctant management that it needn’t be invasive to a program’s design.
As mark already mentioned, just call QObject::connect(). That method ist static in QObject, so that works without problems.
Cool…that’s the first time I’ve seen that done.
OK…now I’m getting a linker error:
- Undefined symbols:
- "vtable for WorkerThread", referenced from:
- WorkerThread::WorkerThread()in main.o
That doesn’t look like a coding problem to me; am I missing a library or something?
You must log in to post a reply. Not a member yet? Register here!




