(seemingly) simple Qt app: creating a progress bar
-
wrote on 12 Feb 2012, 02:38 last edited by
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":http://developer.qt.nokia.com/doc/qt-4.8/qprogressbar.html
...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.
-
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);
QProgressBar bar(0);
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":https://gitorious.org/spdar/spdar/trees/master, but proceed with caution, as this is a very old and crude code :) Works, though.
-
wrote on 12 Feb 2012, 22:06 last edited by
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 [[Doc:QProgressDialog]] can be an alternative too, it suffers from a non running event loop too.
-
wrote on 12 Feb 2012, 22:51 last edited by
Volker: I'm not sure I understand. Are you saying that this isn't feasible?
@while (something)
{
do some work
update to reflect the progress of the work
}
@ -
wrote on 12 Feb 2012, 23:55 last edited by
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.
-
wrote on 13 Feb 2012, 00:20 last edited by
OK, so if I can pursue this a bit further:
- the application, once started is completely compute-bound. No action from the user is needed nor permitted.
- 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.
-
wrote on 13 Feb 2012, 11:55 last edited by
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/Threads_Events_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.
-
wrote on 13 Feb 2012, 17:19 last edited by
OK...I scanned the article you identified. I was taken by this line:
bq. 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?
-
wrote on 13 Feb 2012, 17:40 last edited by
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.
-
wrote on 13 Feb 2012, 17:43 last edited by
OK, thanks, Volker...I guess I've got some reading to do. I appreciate the feedback, as always.
Edit: Volker, I sent you an email with a couple of questions; if you're so inclined to respond, that would be great.
-
wrote on 17 Feb 2012, 00:46 last edited by
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;
}class WorkerThread : public QObject
{
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[])
{
QApplication app (argc, argv);
WorkerThread worker;QProgressBar bar(0);
bar.setRange(0, 100);
bar.setValue(0);
bar.show();
// bar.setValue(percent);return app.exec();
}void WorkerThread::percentChanged(int percent) {}
@ -
wrote on 17 Feb 2012, 11:17 last edited by
On a first glance, that looks good. Despite the fact that you might consider using [[Doc:QFile]]/[[Doc:QTextStream]] for the file operations and [[Doc: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:
@
QProgressBar bar(0);
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.
-
wrote on 17 Feb 2012, 14:36 last edited by
[quote author="Volker" date="1329477431"]On a first glance, that looks good. Despite the fact that you might consider using [[Doc:QFile]]/[[Doc:QTextStream]] for the file operations and [[Doc:QFileInfo]] for getting the file size (instead of your method)[/quote]
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
[quote]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.[/quote]
Oh yeah; I knew that (sort of).
[quote] The signal must be emitted in the run method of your thread:
@
// some kind of signal to be emitted here
emit percentChanged(percent);
@bq. You'll also have to connect that signal to the progress bar:
@
connect(worker, SIGNAL(percentChanged(int)), bar, SLOT(setValue(int)));
@bq. Also, the worker needs to be moved to a thread, and eventually started:
@
QProgressBar bar(0);
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();
@bq. to make the autostart work, you must declare WorkerThread::run() as public slot.[/quote]
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.
-
wrote on 17 Feb 2012, 16:19 last edited by
If you're using connect() outside of a class that's a subclass of QObject, you'll need to use the full name of the static method, "QObject::connect()"
-
wrote on 17 Feb 2012, 16:23 last edited by
Oh, using QFile and friends is much more easier than the stdlib methods - give it a try! :)
As mark already mentioned, just call QObject::connect(). That method ist static in QObject, so that works without problems.
-
wrote on 17 Feb 2012, 16:28 last edited by
[quote author="Volker" date="1329495814"]Oh, using QFile and friends is much more easier than the stdlib methods - give it a try! :) [/quote]
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.
[quote]As mark already mentioned, just call QObject::connect(). That method ist static in QObject, so that works without problems.[/quote]
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?
-
wrote on 17 Feb 2012, 16:32 last edited by
Some missing moc steps.
I would recommend to put the WokerThread class in a separate .h header file (and probably extract the implementation to a .cpp file).
moc is usually not run on the file that contains the main method.
If you have changed your project, do a full rebuild to catch up for all the changes.
-
wrote on 17 Feb 2012, 17:47 last edited by
Oh...excellent! This is very, very encouraging.
EDIT:
Actually, let's just get to the real thing here: this is the main routine in my application:
@#include <iostream>
#include <string>#include "modem.h"
using namespace std;
int main ()
{
Modem modem;
bool clockEnable = HIGH;
bool resetFlag = LOW;int32_t rc = 0;
int32_t i = 0;while (rc == 0)
{
systemClock.setClock(HIGH);
rc = modem.cycle(clockEnable, resetFlag);systemClock.setClock(LOW);
modem.cycle(clockEnable, resetFlag); // no need to check rc on low clockif (++i % 1000 == 0)
cout << "main cycled " << dec << i << " times." << endl;
}return 0;
}
@So...do the guts of this become my run() function? And, what's currently in my example main() essentially goes into my app main()? Is that the gist of it?
Also, I'd like to move as much of the progress bar processing out of main(). I know it's only three lines now, but...once I get this working in my app, I'm planning on adding some stuff to the UI. Any reason I shouldn't pursue this?
Thanks...
-
wrote on 17 Feb 2012, 23:02 last edited by
Yes, the contents of the main method would go into the worker class. Make the Modem and the flags a class variable, and the rest into the run slot. The singal and emit is just like in the dummy example we had before.
[EDIT: the contents of the main method goes to the class, not the method itself, of course :) ]
-
wrote on 17 Feb 2012, 23:12 last edited by
OK, thanks, Volker. On a related subject, I've been experimenting with creating a QMainWindow, but evidently, I don't understand the constructors as well as I thought. The line:
@ QProgressBar bar(0);@
Is creating an object of type QProgressBar named bar, and with no parent, right? So why doesn't this:
@ QMainWindow mainWindow;
QProgressBar bar(*mainWindow);
@Create a QMainWindow, and then a bar whose parent is the QMainWindow? I'm getting a "no matching function" compiler error.
1/72