6

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.

Avni Gupta
  • 81
  • 1
  • 3
  • 7
    Look up QTimer. Also, I refuse to believe that you actually tried to search for this problem and you found nothing. – Matteo Italia Jan 18 '17 at 02:10
  • 1
    Don't be too harsh, @Matteo. When I entered `qt every second` into Google, only the first five links were relevant. Perhaps the OP was scared off by link six, which was some bizarre poetry from a Godophile :-) – paxdiablo Jan 18 '17 at 02:22
  • 1
    And then you need `every two seconds` thus ask a whole different question. – dtech Jan 18 '17 at 04:55

3 Answers3

9

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).

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
4

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

Community
  • 1
  • 1
cppxor2arr
  • 295
  • 2
  • 12
1

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

kablouser
  • 11
  • 1