I\'m learning Qt and I was reading about Threads, Events and QObjects from Qt wiki, and followed the wiki recommendations on how to handle some work in a while condition but
This won't work, because processMessages() is not a SLOT
.
So Declare processMessages() as a private slot and then try.
You don't declare the timer neither the slot. In the header you must declare:
class ... {
QTimer timer;
...
private slots:
void processMessages();
...
};
Then remember to make the SIGNAL-SLOT connection and configure the timer:
connect(&timer, SIGNAL(timeout()), this, SLOT(processMessages()));
timer.setInterval(1000);
timer.start();
Also timer.start(1000);
would be valid...
ANOTHER POSSIBILITY
Other possibility would be to use the timer associated with each Q_OBJECT and overload the timerEvent
:
class ... {
Q_OBJECT
...
protected:
void timerEvent(QTimerEvent *event);
...
};
Then you must implement the timer event as this:
void MyClass::timerEvent(QTimerEvent *event) {
processMessages();
}
And you can configure the timer with a simple call to startTimer(1000);
Where is timer
declared and defined?
If it's local to Foo::connect()
it'll be destroyed before it ever has a chance to fire. Presumably it just needs to be a member object of the Foo
class.
Also keep in mind that QObject
provides it's own simple interface to a timer - just override the protected virtual timerEvent()
function and call QObject's startTimer()
to start getting those timer events. In this case instead of having a slot to receive the timer events, they will just end up at the overridden timerEvent()
function:
protected:
void timerEvent(QTimerEvent *event) {
processMessages();
}
public:
void connect( /* ... */ ) {
// ...
startTimer(1000);
}