How to update a flag value on qpuhbutton click event ?
-
So, your function takes long to execute, right? Then you will only be able to stop it via UI if it does not block the event loop! You can for example call QCoreApplication::processEvents() periodically in your function. Then just implement a slot which sets the flag and connect it to the clicked() signal of another QPushButton.
-
void MyClass::myLongLastingMethod() { flag = false; while(someCondition) { // Do something QCoreApplication::processEvents(); if (flag) break; } } void MyClass::onStopButtonClicked() { flag = true; }
-
Hi Jsulm , its not work in my case because i am using qWait various time in my code. so its block there .
in place of wait what can i use for delay of various second after executing one function then call another.
actually I want to execute some function sequentially after having delay of some seconds one by one.
-
As I said it will only work if you don't block Qt event loop.
Blocking the event loop is usually a really bad idea and is not how Qt applications should be written.
I still don't understand why you need to wait in a function? I would recommend to redesign your application to make use of asynchronous programming.
If you really want to wait you can still use qWait but with smaller timeout in a loop and call QCoreApplication::processEvents() on each iteration. -
A local event loop is an option in this case as well (instead of calling
processEvents
).@Rajni said:
its not work in my case because i am using qWait various time in my code. so its block there .
You shouldn't use that at all.
qWait
is for unit testing, not for production code, and to top that, as @jsulm said, you don't want to block the event loop or your GUI will simply freeze. Either run your lengthy operation in a loop and callQCoreApplication::processEvents
regularly, or use a local event loop to block and schedule calls through it. For example:class SomeClass : public QObject { Q_OBJECT public: Q_INVOKABLE doSomething1() { // Do stuff // ... // Schedule the next batch of work QMetaObject::invokeMethod(this, "doSomething2", Qt::QueuedConnection); } Q_INVOKABLE doSomething2() { // Do more stuff // ... // Exit the blocking local event loop emit finished(); } signals: void finished(); }
Used like this:
SomeClass doWorkObject; QEventLoop loop; QObject::connect(&doWorkObject, &SomeClass::finished, &loop, &QEventLoop::quit); QMetaObject::invokeMethod(&doWorkObject, "doSomething1", Qt::QueuedConnection); loop.exec(); //< Blocks until QEventLoop::quit is called.
How is best, however, really depends on exactly what you want to achieve.
Kind regards.