Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Stop a function with "Stop" button



  • I have a function that runs some calculations and I would like to allow user to stop it with a button.
    In the interface there are two simple button: Start and Stop.

    I don't know exactely what do you need as code, the function is very long... let me know!

    Thank you



  • Mmh... I assume, you are running your calculations in your GUI-Thread? (Or did you explicitly create a worker thread?)

    If that is true, your application can't process GUI-Events as long as the calculation is in progress. You can force your GUI-Thread to process events, if you do the following function within your loop:

    QCoreApplication::processEvents();

    If you do so, your application should first become "kind-of-responsive" again. [Better would be to create a worker thread for your calculation!]

    Next step is, that the Stop-Button sets a flag, that it has been pressed. Then you check this flag within your calculation loop and if it is set, you break out of the loop and stop the calculation.

    I hope this helps!

    Best Regards,
    Tobias



  • In my opinion the question is too vague. Have considered the option to do the calculations in a separate thread using "QThread":https://qt-project.org/doc/qt-5/qthread.html? You can bind a signal from your GUI with a slot of the thread and to terminate it.



  • I have a rule of thumb: "Never use Terminate-Thread!"

    Reason is simple: you never know, when exactly i gets terminated, so application state after termination may be undefined, for example: what happens if you terminate the thread while it is inside a Critical Section? It will never leave it... and the critical section will be blocked forever...



  • [quote author="topse" date="1398855116"]I have a rule of thumb: "Never use Terminate-Thread!"

    Reason is simple: you never know, when exactly i gets terminated, so application state after termination may be undefined, for example: what happens if you terminate the thread while it is inside a Critical Section? It will never leave it... and the critical section will be blocked forever...[/quote]

    As I said before the question is too vague. The solution depends on the exact situation.
    Here a good article about "Keeping the GUI Responsive":http://doc.qt.digia.com/qq/qq27-responsive-guis.html with Qt. As you can see several approaches are described, including a way using a worker thread. There a lot of well known paradigms to escape from deadlocks and to handle critical sections and resource in multithreaded applications.


Log in to reply