Qt How to kill a timer started using startTimer() API? - c++

I update a count down timer using timerEvent(QTimerEvent *e) once I am done I call the killTimer(timerID) but the timerEvent() is still being called.
So what's the proper way to kill it?
The Code:
void MainWindow::timerEvent(QTimerEvent *e)
{
Q_UNUSED(e);
static uint16_t u16RemTime = MAX_WARMUP_TIME_IN_SECS;
if((true == isWarmUpStarted) && (u16RemTime > 0))
{
u16RemTime--;
objptrSplashScreen->SetTime(u16RemTime);
}
else
{
//Still running
qWarning("\n\n\n\n\n WARM UP TIMER RUNNING \n\n\n\n\n");
killTimer(warmUpTimerID);
}
}
If it helps. I have two such timers running in two different classes in the same GUI thread. How would I go about killing it?

timerEvent receives all timers' events. In order to differ them QTimerEvent class have int timerId() const method. So your event should look like this:
void MainWindow::timerEvent(QTimerEvent *e)
{
if (e->timerId() != warmUpTimerID)
return;
static uint16_t u16RemTime = MAX_WARMUP_TIME_IN_SECS;
if((true == isWarmUpStarted) && (u16RemTime > 0))
{
u16RemTime--;
objptrSplashScreen->SetTime(u16RemTime);
}
else
{
//Still running
qWarning("\n\n\n\n\n WARM UP TIMER RUNNING \n\n\n\n\n");
killTimer(warmUpTimerID);
}
}

If you use a QTimer or QBasicTimer, you can call the stop() on one of those.

You need to make sure that a particular timerEvent invocation is related to your timer.
QBasicTimer is a nice convenience wrapper around a timer id, you could use it instead of the raw id.
Static variables in members of classes that can be potentially reused are a source of nasty bugs.
isWarmupStarted is redundant, its value is identical to m_warmupRemaining > 0.
You're not saving anything by explicitly using a 16 bit unsigned integer for the remaining time counter. Just use an int.
The style that explicitly mentions types in variable names is, well, if your employer isn't forcing you to use it, don't use it. It's the compiler's job to keep track of such things, not yours, and it's not C and winapi where things sometimes got hairy if you didn't do that.
Thus:
class MainWindow : public QMainWindow {
Q_OBJECT
QSplashScreen * m_splashScreen;
QBasicTimer m_warmupTimer;
int m_warmupRemaining;
void timerEvent(QTimerEvent * ev) {
if (ev->timerId() != m_warmupTimer.timerId()) return;
// No need to call the empty QMainWindow::timerEvent(ev).
// All timerEvent implementations in public Qt classes are empty,
// to make your life easier.
if (m_warmupRemaining > 0) {
m_warmupRemaining --;
m_splashScreen->SetTime(m_warmupRemaining);
} else {
m_warmupTimer.stop();
}
}
};

Related

QT Multi-threading & Updating GUI

I'm currently updating an existing codebase designed to be used with a GTK GUI to QT, so that it can implement multi threading, as the functions take hours to complete.
This codebase makes frequent calls to a function display(std::string), for the purpose of updating a text display widget. I redefined this function for the new QT version:
In Display.cpp:
void display(std::string output)
{
//
MainWindow * gui = MainWindow::getMainWinPtr(); //Gets instance of GUI
gui->DisplayInGUI(output); //Sends string to new QT display function
}
In MainWindow.cpp:
void MainWindow::DisplayInGUI(std::string output)
{
//converts output to qstring and displays in text edit widget
}
void MainWindow::mainFunction(){
//calls function in existing codebase, which itself is frequently calling display()
}
void MainWindow::on_mainFunctionButton_released()
{
QFuture<void> future = QtConcurrent::run(this,&MainWindow::mainFunction);
}
If I run the main function in a new thread, display(std::string) won't update the GUI until the thread completes. I understand why; the GUI can only be updated in the main thread. Everything else functions as intended.
What I want to implement, but I'm not sure how, is having display(std:string) send a signal back to the main thread to call MainWindow::DisplayInGUI(output_text) with the string that was passed to the display() function. I believe this is the correct way to do it, but correct me if I'm wrong. I want to avoid changing the existing codebase at all costs.
EDIT: I should add that for some dumb reasons entirely out of my control, I am forced to use C++98 (yeah, I know)
You must schedule the code that does UI calls to run in the main thread. I use a simple and easy to use wrapper for that:
#include <QApplication>
#include <QtGlobal>
#include <utility>
template<typename F>
void runInMainThread(F&& fun)
{
QObject tmp;
QObject::connect(&tmp, &QObject::destroyed, qApp, std::forward<F>(fun),
Qt::QueuedConnection);
}
You can now run code (using a lambda in this example, but any other callable will work) in the main thread like this:
runInMainThread([] { /* code */ });
In your case:
void display(std::string output)
{
runInMainThread([output = std::move(output)] {
MainWindow* gui = MainWindow::getMainWinPtr();
gui->DisplayInGUI(output);
});
}
Or you can leave display() as is and instead wrap the calls to it:
runInMainThread([str] { display(std::move(str)); );
The std::move is just an optimization to avoid another copy of the string since you should not pass the string by reference in this case (it would be a dangling reference once the string object goes out of scope.)
This is not a high performance inter-thread communication mechanism. Every call will result in the construction of a temporary QObject and a temporary signal/slot connection. For periodic UI updates, it's good enough and it allows you to run any code in the main thread without having to manually set up signal/slot connections for the various UI update operations. But for thousands of UI calls per second, it's probably not very efficient.
First of all: there's no way to make the getMainWinPtr method thread-safe, so this pseudo-singleton hack should probably go away. You can pass around some application-global context to all the objects that do application-global things like provide user feedback. Say, have a MyApplication : QObject (don't derive from QApplication, it's unnecessary). This can be passed around when new objects are created, and you'd then control the relative lifetime of the involved objects directly in the main() function:
void main(int argc, char **argv) {
QApplication app(argc, argv);
MainWindow win;
MyApplication foo;
win.setApplication(&foo);
// it is now guaranteed by the semantics of the language that
// the main window outlives `MyApplication`, and thus `MyApplication` is free to assume
// that the window exists and it's OK to call its methods
...
return app.exec();
}
Of course MyApplication must take care that the worker threads are stopped before its destructor returns.
To communicate asynchronous changes to QObject living in (non-overloaded) QThreads (including the main thread), leverage the built-in inter-thread communication inherent in Qt's design: the events, and the slot calls that traverse thread boundaries.
So, given the DisplayInGUI method, you need a thread-safe way of invoking it:
std::string newOutput = ...;
QMetaObject::invokeMethod(mainWindow, [mainWindow, newOutput]{
mainWindow->displayInGUI(newOutput);
});
This takes care of the thread-safety aspect. Now we have another problem: the main window can get hammered with those updates much faster than the screen refresh rate, so there's no point in the thread notifying the main window more often than some reasonable rate, it'll just waste resources.
This is best handled by making the DisplayInGUI method thread-safe, and leveraging the timing APIs in Qt:
class MainWindow : public QWidget {
Q_OBJECT
...
static constexpr m_updatePeriod = 1000/25; // in ms
QMutex m_displayMutex;
QBasicTimer m_displayRefreshTimer;
std::string m_newDisplayText;
bool m_pendingRefresh;
...
void timerEvent(QTimerEvent *event) override {
if (event->timerId() == m_displayRefreshTimer.timerId()) {
QMutexLocker lock(&m_displayMutex);
std::string text = std::move(m_newDisplayText);
m_pendingRefresh = false;
lock.release();
widget->setText(QString::fromStdString(text));
}
QWidget::timerEvent(event);
}
void DisplayInGUI(const std::string &str) {
// Note pass-by-reference, not pass-by-value. Pass by value gives us no benefit here.
QMutexLocker lock(&m_displayMutex);
m_newDisplayText = str;
if (m_pendingRefresh) return;
m_pendingRefresh = true;
lock.release();
QMetaObject::invokeMethod(this, &MainWindow::DisplayInGui_impl);
}
private:
Q_SLOT void DisplayInGui_impl() {
if (!m_displayRefreshTimer.isActive())
m_displayRefreshTimer.start(this, m_updatePeriod);
}
};
In a more complex situation you'd likely want to factor out the cross-thread property setting to some "adjunct" class that would perform such operations without the boilerplate.
You could take advantage of the fact that QTimer::singleShot has an overload which, when called with a zero time interval, allows you to effectively schedule a task to be run on a specified thread during that thread's next idle slot...
void QTimer::singleShot(int msec, const QObject *context, Functor functor);
So your MainWindow::mainFunction could be something along the lines of...
void MainWindow::mainFunction ()
{
...
std::string output = get_ouput_from_somewhere();
QTimer::singleShot(0, QApplication::instance(),
[output]()
{
display(output);
});
...
}

How to wait for signal in long running method?

At the moment I am developing a simple programming language on the basis of flex&bison.
For this I first build the abstract syntax tree (AST) and continue with its evaluation. During the evaluation it shall be possible to receive user input. The user input is done in a Qt-GUI. The ast-evaluation-procedure runs in a thread-worker-object, that is created by the GUI.
My problem: Which one is the best way, to "block" the running flex&bison evaluation-procedure to then receive a user input from the GUI and afterwards continue with executing the procedure?
Unfortunately I have no idea, how to split the evaluation procedure into two parts to catch the user input-signal from the GUI and then to continue with the "splitted procedure" in a slot.
My current solution works (to my opinion poor) with an infinite loop within the evaluation procedure and this runs until a boolean member variable (_hasUserInput) in the thread worker-object is set to true. After the user input the GUI emits the signal. The corresponding slot is inside the thread worker-object. The slot receives the user input e.g. as a QString and sets a corresponding member variable. Additionally the boolean variable is set to true, so the infinite loop of the evaluation-procedure can be left, the user input can be processed and the evaluation can be continued.
Functional principle:
GUI --> starts Thread (Worker-Object) --> starts the longterm running procedure
Example in pseudo code:
class ThreadWorker : public QObject {
...
// Slot, that reacts to the signal from the GUI
void userInput(const QString &input) {
_userInput = input;
_hasUserInput = true;
}
// evaluation-procedure
void doEvaluation() {
// evaluation of the AST
...
emit userInputRequired();
while (!hasUserInput){ // Check if user input has been done
qApp -> processEvents(); // to react to events
}
do something with user input;
continue valuation; // Processing of user input and continuation of the procedure
}
...
};
I tried to give a description of my problem as good as possible and hope it worked. Please ask, in case you need more detailed information.
Thanks very much in advance for your assistance!
Since you've already factored out the worker into a QObject, you should never need to call processEvents(). Instead, break down the AST evaluation into small chunks that are performed as long as necessary. I've also made the public interface thread-safe - thus you can call it directly from any thread.
// see https://stackoverflow.com/a/40382821/1329652
bool isSafe(QObject * obj);
template <typename Class, typename... Args> void postCall(Class * obj, void (Class::*method)(Args...), Args&& ...args);
class ASTWorker : public QObject {
Q_OBJECT
QBasicTimer m_evaluateTimer; // a bit lower overhead than QTimer
void timerEvent(QTimerEvent * ev) override {
if (ev->timerId() == m_evaluateTimer.timerId())
evaluateImpl();
}
void evaluateImpl() {
bool evaluationDone = {};
QThread::msleep(10); // emulate evaluating a chunk of AST
if (!evaluationDone && !m_evaluateTimer.isActive())
m_evaluateTimer.start(0, this);
else if (evaluationDone)
m_evaluateTimer.stop();
}
public:
using QObject::QObject;
/// Thread-safe
Q_SLOT void setUserInput(const Data & data) {
if (!isSafe(this))
return postCall(this, &ASTWorker::setUserInput, data);
QThread::msleep(1); // emulate processing user data
}
/// Thread-safe
Q_SLOT void evaluate() {
if (!isSafe(this))
return postCall(this, &ASTWorker::evaluate, data);
evaluateImpl();
}
};

Is there a better way to make an EventManager

I made a little code for my EventManager, it works correctly, but the thing is, I created it with a lot of copy-paste, and I think that every time you start doing copy-paste on a few lines, your code is badly designed.
So, having done a lot of copy-paste on that EventManager, I think it's time to find out if there is another way to make it (and there probably is, and probably better).
What I achieved is that when an Event happens (window.pollEvent(event)), it calls the onEvent(sf::Event, sf::RenderWindow*) method of the EventManager class, and for every event I need to listen, I call all instances of the listener.
Here's the class :
public:
void registerKeyPressed(std::shared_ptr<KeyPressedEventListener> listener);
void registerWindowResized(std::shared_ptr<WindowResizedEventListener> listener);
void registerWindowFrameUpdate(std::shared_ptr<WindowFrameUpdateEventListener> listener);
private:
std::vector<std::shared_ptr<KeyPressedEventListener>> m_keyPressedListeners;
std::vector<std::shared_ptr<WindowResizedEventListener>> m_windowResizedListeners;
std::vector<std::shared_ptr<WindowFrameUpdateEventListener>> m_windowFrameUpdateListeners;
So, the thing is, it is a lot of code for only 3 listeners (I currently have 6, but it's not useful to show them as the code is always similar).
My problem is that I want a class to be able to listen to one, two or more events at a time, so all my listeners have a different function that's called when the event happens. For example, these three listeners have the functions onKeypressed(sf::Event);, onWindowResized(sf::Event, sf::RenderWindow* window); and onFrameUpdate(sf::RenderWindow* window);. That's the only way I found to make this code work.
It actually works, but I'd like to make something better, because it's a lot of code for every event :
void EventManager::onEvent(sf::Event event, sf::RenderWindow* window) { // The window argument is used further, but it's not useful to show it here as the code is quite the same
switch (event.type) {
case sf::Event::Resized:
for (unsigned int i = 0; i < m_windowResizedListeners.size(); i++) {
if (m_windowResizedListeners.at(i)->onWindowResized(event)) break; // The events return a bool value : True if the loop has to stop (for an error, for example), false otherwise. I always return false unless an error happen, but it's in case I need to stop it.
}
break;
}
}
void EventManager::registerWindowResized(std::shared_ptr<WindowResizedEventListener> listener) {
m_windowResizedListeners.push_back(listener);
}
And I have to duplicate this code for every event. If there's a bug, you understand it'll be a lot of work to correct it, so I hoped you could help me find a better way to achieve it.
Thank you for your help.
You could use a common class:
class EventHandler{
public:
virtual void handle(sf::RenderWindow &window) = 0;
};
class EventManager {
public:
void registerKeyPressed(std::shared_ptr<EventHandler> listener);
void registerWindowResized(std::shared_ptr<EventHandler> listener);
void registerWindowFrameUpdate(std::shared_ptr<EventHandler> listener);
private:
std::vector<std::shared_ptr<EventHandler>> m_keyPressedListeners;
std::vector<std::shared_ptr<EventHandler>> m_windowResizedListeners;
std::vector<std::shared_ptr<EventHandler>> m_windowFrameUpdateListeners;
}
You can now define a map in the class, the key is the event type and the value is his listener's vector.
std::map<int,std::vector<std::shared_ptr<EventHandler>>*> eventType;
}
//...
EventManager::EventManager(){
eventType[sf::EventType::Resized] = &m_windowResizedListeners;
eventType[sf::EventType::KeyPressed] = &m_keyPressedListeners;
//Keep going...
}
So now, the onEvent function is pretty straightforward:
void EventManager::onEvent(sf::Event event, sf::RenderWindow* window) {
std::vector<std::shared_ptr<EventHandler>>* ptr = eventType[event.type];
for (int i = 0;i < ptr->size();i++)
(*ptr)[i]->handle(window);
}
Let's put an example:
class SettingsSaver : public EventHandler{
public:
void handle(sf::RenderWindow &window) override {
std::cout << "I am saving the state in the hardrive before of exit" << std::endl;
}
}
class MoveHero : public EventHandler{
public:
void handle(sf::RenderWindow &window) override {
std::cout << "I am moving the character" << std::endl;
}
}
// Main
std::shared_ptr<EventHandler> settingsSaver(new SettingsSaver);
std::shared_ptr<EventHandler> moveHero(new MoveHero);
EventManager manager;
manager.registerWindowClosed(settingsSaver);
manager.registerKeyPressed(moveHero);

If you stop a QTimer, will it emit a timeout() signal?

I'm trying to understand the operation of a QTimer. I have things triggered off timeout() signals, but I am unable to find in the documentation if a timeout() signal is emitted if I stop the timer early.
Basically, how can I force a timeout() before the timer finishes counting? Just hack by restarting the timer with the minimum ms increment?
myTimer->start(1);
http://qt-project.org/doc/qt-5/qtimer.html#timeout
In neither Qt 4 nor Qt 5 can you directly emit QTimer::timeout from outside of the class. It's a private signal: in Qt 4, it's declared as private, in Qt 5, it's declared with an argument of a private type QObjectPrivate.
You can invoke it, though:
// fast, guaranteed to work in Qt 4 and 5
myTimer->QTimer::qt_metacall(QMetaObject::InvokeMetaMethod, 5, {});
// slower, has to look up the method by name
QMetaObject::invokeMethod(myTimer, "timeout");
In Qt 5, the moc-generated QTimer::qt_static_metacall constructs the private argument for us:
//...
case 0: _t->timeout(QPrivateSignal()); break;
You can also make the timer act as if it had timed out by sending it a timer event:
void emitTimeout(QTimer * timer) {
Q_ASSERT(timer);
QTimerEvent event{timer->timerId()};
QCoreApplication::sendEvent(timer, &event);
}
Both methods work on both Qt 4 and Qt 5.
Since you're looking to emit a timeout on stopping an active timer, the solutions would be, respectively:
void emitTimeoutAndStop(QTimer * timer) {
Q_ASSERT(timer);
Q_ASSERT(QAbstractEventDispatcher::instance()); // event loop must be on the stack
if (!timer->isActive()) return;
timer->QTimer::qt_metacall(QMetaObject::InvokeMetaMethod, 5, {});
timer->stop();
}
or
void emitTimeoutAndStop(QTimer * timer) {
Q_ASSERT(timer);
Q_ASSERT(QAbstractEventDispatcher::instance()); // event loop must be on the stack
if (!timer->isActive()) return;
QTimerEvent event{timer->timerId()};
QCoreApplication::sendEvent(timer, &event);
timer->stop();
}
The signals will be emitted immediately, and not by Qt code from the event loop. This shouldn't be a problem, since emitTimeoutAndStop will be invoked with an event loop on the stack. We assert that fact. If you wish to support invoking emitTimeoutAndStop from code tied to the same timer's timeout signal without reentering said code, then you have to use the ChattyTimer below, or the solution from another answer.
If all you need isn't quite a timer, but just an immediate, single-emission signal, QObject::destroyed is useful for that purpose. It will be emitted at the end of the block, where source goes out of scope and is destructed.
{ QObject source;
connect(&source, &QObject::destroyed, ...); }
Alternatively, you can have a small helper class:
// signalsource.h
#pragma once
#include <QObject>
class SignalSource : public QObject {
Q_OBJECT
public:
Q_SIGNAL void signal();
SignalSource(QObject * parent = {}) : QObject(parent) {}
};
Since you can connect multiple signals to a single receiver, perhaps it would make things clearer to connect both a timer and such a signal source to the receiver, instead of trying to hack around timer's behavior.
On the other hand, if such "signaling upon stopping" timer is something you find useful in several places, it'd be better to actually implement it as a dedicated class - it's not all that hard. Re-using the QTimer class is not possible, since the stop() slot is not virtual, and thus ChattyTimer is not Liskov-substitutable for a QTimer. This would be a bug waiting to happen - in the class of bugs that are hard to find.
There are several behavioral details that demand attention. This perhaps indicates that changing the behavior of something as fundamental as a timer is tricky - you never know what code might make assumptions that are obviously correct in QTimer, but not so when stop() might emit a timeout. It is a good idea to have all this in a class that is not-a QTimer - it really is not!
As in QTimer, the timeout event is always emitted from the event loop. To have it emitted immediately from stop(), set immediateStopTimeout.
There are two generalizations possible of isActive behavior upon stop (vs. that of QTimer):
becomes false immediately after stop returns, even if the final timeout will be emitted later, or
indicates whether timeout events may be emitted by the event loop, and will remain true after a stop() if the final timeout signal is deferred.
I chose the first behavior to be the default. Set activeUntilLastTimeout to select the second behavior.
There are three generalizations possible of the behavior of each of timerId and remainingTime upon stop (vs. that of QTimer):
returns -1 when isActive() is false, or a valid identifier/time otherwise (i.e. follows chosen isActive() behavior),
becomes -1 immediately after stop returns, even if the final timeout will be emitted later,
returns a valid id/time whenever timeout events may still be emitted by the event loop.
I chose the first behavior for both timerId and remainingTime, and it is not otherwise configurable.
// https://github.com/KubaO/stackoverflown/tree/master/questions/chattytimer-25695203
// chattytimer.h
#pragma once
#include <QAbstractEventDispatcher>
#include <QBasicTimer>
#include <QTimerEvent>
class ChattyTimer : public QObject {
Q_OBJECT
Q_PROPERTY(bool active READ isActive)
Q_PROPERTY(int remainingTime READ remainingTime)
Q_PROPERTY(int interval READ interval WRITE setInterval)
Q_PROPERTY(bool singleShot READ singleShot WRITE setSingleShot)
Q_PROPERTY(Qt::TimerType timerType READ timerType WRITE setTimerType)
Q_PROPERTY(bool immediateStopTimeout READ immediateStopTimeout WRITE setImmediateStopTimeout)
Q_PROPERTY(bool activeUntilLastTimeout READ activeUntilLastTimeout WRITE setActiveUntilLastTimeout)
Qt::TimerType m_type = Qt::CoarseTimer;
bool m_singleShot = false;
bool m_stopTimeout = false;
bool m_immediateStopTimeout = false;
bool m_activeUntilLastTimeout = false;
QBasicTimer m_timer;
int m_interval = 0;
void timerEvent(QTimerEvent * ev) override {
if (ev->timerId() != m_timer.timerId()) return;
if (m_singleShot || m_stopTimeout) m_timer.stop();
m_stopTimeout = false;
emit timeout({});
}
public:
ChattyTimer(QObject * parent = {}) : QObject(parent) {}
Q_SLOT void start(int msec) {
m_interval = msec;
start();
}
Q_SLOT void start() {
m_stopTimeout = false;
m_timer.stop(); // don't emit the signal here
m_timer.start(m_interval, m_type, this);
}
Q_SLOT void stop() {
if (!isActive()) return;
m_timer.stop();
m_stopTimeout = !m_immediateStopTimeout;
if (m_immediateStopTimeout)
emit timeout({});
else // defer to the event loop
m_timer.start(0, this);
}
Q_SIGNAL void timeout(QPrivateSignal);
int timerId() const {
return isActive() ? m_timer.timerId() : -1;
}
bool isActive() const {
return m_timer.isActive() && (m_activeUntilLastTimeout || !m_stopTimeout);
}
int remainingTime() const {
return
isActive()
? QAbstractEventDispatcher::instance()->remainingTime(m_timer.timerId())
: -1;
}
int interval() const { return m_interval; }
void setInterval(int msec) {
m_interval = msec;
if (!isActive()) return;
m_timer.stop(); // don't emit the signal here
start();
}
bool singleShot() const { return m_singleShot; }
void setSingleShot(bool s) { m_singleShot = s; }
Qt::TimerType timerType() const { return m_type; }
void setTimerType(Qt::TimerType t) { m_type = t; }
bool immediateStopTimeout() const { return m_immediateStopTimeout; }
void setImmediateStopTimeout(bool s) { m_immediateStopTimeout = s; }
bool activeUntilLastTimeout() const { return m_activeUntilLastTimeout; }
void setActiveUntilLastTimeout(bool s) { m_activeUntilLastTimeout = s; }
};
If you stop a QTimer, will it emit a timeout() signal?
No.
Basically, how can I force a timeout() before the timer finishes
counting? Just hack by restarting the timer with the minimum ms
increment?
Call stop() on the timer, and then cause the signal to be emitted yourself. You could do this by subclassing QTimer and calling a method in your QTimer subclass that emits the signal:
void MyQTimer :: EmitTimeoutSignal() {emit timeout();}
… but if you don't want to go to the bother of making a subclass, an easier approach would be to add a signal to your own class and connect that signal to the QTimer object's timeout() signal (do this only once of course):
connect(this, SIGNAL(MyTimeoutSignal()), myTimer, SIGNAL(timeout()));
… and then your stop-and-fire method would could be done like this:
myTimer->stop();
emit MyTimeoutSignal();
It's actually quite easy to do this, at least in 4.8 and later (not sure about earlier versions): simply setInterval(0) (much like you suggest in your question, although there's no need to stop the timer and restart it).
This app will immediately print "Timer expired" and exit:
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(1000 * 60 * 60); // one hour
QObject::connect(
&timer, &QTimer::timeout,
[&]()
{
std::cout << "Timer expired" << std::endl;
app.exit();
});
QTimer::singleShot(
0, //trigger immediately once QtEventLoop is running
[&]()
{
timer.start();
timer.setInterval(0); // Comment this out to run for an hour.
});
app.exec();
}

Application->Processmessages in QT?

In Borland 6 I often use this to unstuck program action:
Application->Processmessages();
Now, with QT 4.8.1, I don't have found in this foreign (for me) documentation of QT.
Can anyone help me?
In Qt, you'd use the static function QApplication::processEvents().
Alas, your issue is that the design of your code is broken. You should never need to call processEvents simply to "unstuck" things. All of your GUI code should consist of run-to-completion methods that take a short time (on the order of single milliseconds: ~0.001s). If something takes longer, you must split it up into smaller sections and return control to the event loop after processing each section.
Here's an example:
class Worker: public QObject
{
Q_OBJECT
int longWorkCounter;
QTimer workTimer;
public:
Worker() : ... longWorkCounter(0) ... {
connect(workTimer, SIGNAL(timeout()), SLOT(longWork());
}
public slots:
void startLongWork() {
if (! longWorkCounter) {
workTimer.start(0);
}
}
private slots:
void longWork() {
if (longWorkCounter++ < longWorkCount) {
// do a piece of work
} else {
longWorkCounter = 0;
workTimer.stop();
}
}
};
A zero-duration timer is one way of getting your code called each time the event queue is empty.
If you're calling third party blocking library code, then the only (unfortunate) fix is to put those operations into slots in a QObject, and move that QObject to a worker thread.