I am new to qt development and facing a problem. I want to call a function updateCompass every 1 second which updates the compass value already drawn in widget.
I need to know how and where to call the function.
I am new to qt development and facing a problem. I want to call a function updateCompass every 1 second which updates the compass value already drawn in widget.
I need to know how and where to call the function.
Qt has a specific method for doing exactly this, by using the QTimer
class.
It allows you to create a timer (one-shot or periodic) and connect its timeout
signal to whatever slot (function) you need to weave your magic.
In fact, that linked page has exactly the code you need to use to perform your desired function:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
This will result in your update
function being called once a second (within the limits imposed by Qt re accuracy and so on).
Example, of your case.
QTimer *timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(updateCompass()));
timer->start(1000);
This calls updateCompass()
every second.
These links may be helpful to you. QTimer & Using QTimer
QTimer is ok for applications that don't care about update frequency (it can fluctuate).
For example, if you making an OpenGL program that updates each frame to animate something, you want to sync the update with the monitor's refresh rate (vsync).
To use vsync implement a class that derives from QWindow
or QOpenGLWindow
. Then at the end of your update function call requestUpdate
https://doc.qt.io/qt-5/qwindow.html#requestUpdate
"[something about the update function] This is a slot so it can be connected to a QTimer::timeout() signal to perform animation. Note however that in the modern OpenGL world it is a much better choice to rely on synchronization to the vertical refresh rate of the display." - from https://doc.qt.io/qt-5/qopenglwindow.html