Hi all.
I have a question about how to show some task progress. Here is my story:
I needed to create a "task", that runs a long-time job ( simulated by cycle
over sleep()s in example code ) and shows the progress.
I have tried 2 ways to do this, but none is the best. I'll be happy if someone
tell me the right way.
Create primitive dialog with progressbar and slider. It will be used in
following cases:
QDialog d = new QDialog();
QLayout l = new QFormLayout(d);
QProgressBar b = new QProgressBar();
l.addWidget(b);
QSlider s = new QSlider();
l.addWidget(s);
Way 1 - job in thread:
----------------------
// show dialog
d.show();
// this is my job. It emits sigProgressChanged(). Every step it sleeps
for
// 2 seconds to simulate a long-time job.
class Job extends QSignalEmitter implements Runnable {
public Signal1<Integer> sigProgressChanged = new Signal1<Integer>();
public void run() {
for ( int i = 0; i < 30; i++ ) {
// do work
Thread.sleep(2000);
// emit progress
sigProgressChanged.emit(i);
// show message - this will crash the app, because out of
main loop
QMessageBox.info(...)
}
}
}
// create, connect and start the job in separate thread
Job j = new Job();
j.sigProgressChanged.connect(b, "setValue(int)");
QThread t = new QThread(j);
t.start();
// dialog will be exec()uted, so main loop will not be broken
d.exec();
t.join();
advantages:
- gui is working smoothly
disadvantages:
- too much of code. Nested class, threading, ...
- too many signals (at least 2 - progress changed and job
done, because executed dialog must be closed
when job has finished. Number of signals is growing if
you have another special needs ).
- I can't do anything with gui from within the thread (
show the error messages etc... ).
It throws exceptions about out-of-main-loop and app
(probably) crashes.
Way 2 - calling processEvents():
----------------------
// only show, do not exec the dialog
d.show();
// job loop
for ( int i = 0; i < 30; i++ ) {
// simulate work
Thread.sleep(2000);
// set progress
b.setValue(i);
// process events
QApplication.processEvents();
// show message - no problem here
QMessageBox.info(...)
}
advantages:
- I can show the message and do anything with gui
- simple and clear code without "magic" (and for non-qt
programmer hidden) signals
disadvantages:
- gui is freezing, because it is updated in 2s steps
I think right solution is somewhere between those ways, but I can't find it.
Anybody helps?
Thank you
--
Dusan
_______________________________________________
Qt-jambi-interest mailing list
[email protected]
http://lists.trolltech.com/mailman/listinfo/qt-jambi-interest