Hello everybody,

I'm quite new to Qt, but I'm going to start to love it. Unfortunately I have a problem I could not solve by myself, even not after some days of thinking and experiments. So it would be very nice if someone could help me with expert knowledge, please.

My scenario:
I have a loop in which I am calculating some stuff. When the user presses a button to start it the GUI freezes until the loop is done. In many forums they say "please use qApp->processEvents()" and it will be fine.

But:
When I do not use "qApp->processEvents()" the loop takes about 2 or 3 secs. With "qApp->processEvents()" it takes about 1 minute!! (if I call "qApp->processEvents()" in every loop step). When I use "qApp->processEvents()" only every 100.000 step the GUI starts to "stutter" again.

My dream:
The user presses a button. The loop begins to solve the problem, ends after the 2 or 3 seconds. During the loop calculation the user can continue to use the GUI without any "stuttering".

My example code:
The user can press button A to increment an int-value, lets say "a". Two other buttons start a loop in which another int-value - say b - is incremented. When the user starts the "b-loop" it is not possible to press Button A until the "b-loop" is done. This is not what I want.
A solution without a thread and with a thread is included (the "two buttons"). Both do not behave as I would like it.

I am very thankful for any help!

Regards
Matty23

Qt Code:
  1. #include <QThread>
  2.  
  3. #include "qt_thread.h"
  4.  
  5. int a = 0;
  6. int b = 0;
  7.  
  8. Qt_Thread *q;
  9.  
  10. class MyThread : public QThread
  11. {
  12. public:
  13. void run();
  14. };
  15.  
  16. void MyThread::run()
  17. {
  18. b = 0;
  19.  
  20. while (b < 1000000){
  21. b++;
  22. q->setb(b);
  23.  
  24. //qApp->processEvents();
  25. }
  26. exec();
  27. }
  28.  
  29.  
  30.  
  31. Qt_Thread::Qt_Thread(QWidget *parent)
  32. : QWidget(parent)
  33. {
  34. ui.setupUi(this);
  35.  
  36. q = this;
  37.  
  38. connect(ui.pbIncA, SIGNAL(clicked()), this, SLOT(pbIncAClicked()));
  39. connect(ui.pbWithoutThread, SIGNAL(clicked()), this, SLOT(pbWithoutThreadClicked()));
  40. connect(ui.pbWithThread, SIGNAL(clicked()), this, SLOT(pbWithThreadClicked()));
  41. }
  42.  
  43.  
  44.  
  45. void Qt_Thread::pbWithoutThreadClicked()
  46. {
  47. b = 0;
  48.  
  49. while (b < 1000000){
  50. b++;
  51. ui.lbb->setText( QString("%1").arg(b) );
  52. }
  53. }
  54.  
  55. void Qt_Thread::pbWithThreadClicked()
  56. {
  57. MyThread m;
  58. m.run();
  59. }
  60.  
  61. void Qt_Thread::setb(int b)
  62. {
  63. ui.lbb->setText( QString("%1").arg(b) );
  64. }
  65.  
  66. void Qt_Thread::pbIncAClicked()
  67. {
  68. a++;
  69. ui.lba->setText( QString("%1").arg(a) );
  70. }
  71.  
  72.  
  73. Qt_Thread::~Qt_Thread()
  74. {
  75.  
  76. }
To copy to clipboard, switch view to plain text mode