c++qtqtimer

How to interrupt the execution of a function in C++/Qt


I'm working on implementing a "tutorial mode" on a software that uses C++ and Qt. To this end, I need to rotate a GL view to show the user that it can move. In order to do a smooth rotation, I used the singleShot method from QTimer to call every 25 ms a slot that increases the rotation by 5. (Don't know if it's the best way, I'm quite new to this!)

Here is the code:


void myWidget::rotateCamera() {
    for (int i = 0; i < 100; i++) {
        QTimer::singleShot(25 * i, this, &myWidget::rotateCameraAutomatic);
    }
}

Problem is that I want to stop the tutorial (and by extension, the rotation) if the user clicks on a button, but I don't know how to stop the execution of this function if a certain event occurs / signal is emitted.

I tried to look into the QEventLoop Class but none of my experiments worked out. I thought that the QEventLoop slot quit would interrupt my function but it does the opposite...

Do you know how I can exit the function before all the QTimers are over, or if there is a better way to code this?


Solution

  • Don't schedule 100 single-shot callbacks all at once. Instead, call QTimer::singleShot() one time, and then in rotateCameraAutomatic() (or whatever method-slot it is the QTimer/singleShot will call) you can decide whether or not to call QTimer::singleShot() again.

    i.e. if you want the tutorial to keep going, you'd call singleShot() again; if not, then don't.