Search code examples
c++qtqwidgetqtimer

Qt - execution of simple loop is slowing down gradually


I have loop inside my main window code, that is simply changing the colour of some text-boxes on screen. It is simply for(int i=0; i<200; i++), but I'd like to make every colour change visible to the user, so inside the loop I've tried to add sth like a 10ms pause, so every execution is visible on screen.

I used this:

      QTimer t;
      t.start(10);
      QEventLoop loop;
      connect(&t, SIGNAL(timeout()), &loop, SLOT(quit()));
      loop.exec();

The problem is, that I'd like to have this 10ms pace constantly, so the whole operation will take about ~2 seconds. Unfortunately, it slows down gradually, so hard, that the last ~20 executions takes even about 1 second each

It looks rather decently when i<20~50, adding more makes it significantly slowing...

I thought about my not-really-brand-new PC, but it is really simple operation to be done, so I don't really think it is because of my slow pc. I'm assume my approach is wrong


PS. During the execution, ram usage for my app is about ~21MB, and cpu about 20-30%


Solution

  • It is not good way to achieve something. QTimer is enough to this task. For example:

     QTimer *t = new QTimer;//without loops and sleeping
     connect(t, SIGNAL(timeout()), this, SLOT(someSlot()));
     t->start(10);
    

    Create someSlot and in this slot change color and do other tasks. To stop timer after 2 seconds, you can use counter instead of using system time.

    void MainWindow::someSlot()
    {
        //do something
    }
    

    Also consider that 10 ms is very very fast, human eyes not able to catch so fast changing. Try to use longer value.