Qtimer Signal Slot Example

Qtimer Signal Slot Example 4,6/5 4642 reviews

Our app's UI is finished, so now we'll create a timer and implement our countdown.

  1. Qt5 Qtimer
  2. Qtimer Signal Slot Examples
  3. Qt Qtimer Example
  4. Qtimer Timeout
  5. Qtimer Update Ui

C (Cpp) QTimer::start - 30 examples found. These are the top rated real world C (Cpp) examples of QTimer::start extracted from open source projects. You can rate examples to help us improve the quality of examples. As you might have seen in the previous example, the slot was just declared as public and not as slot. Qt will indeed call directly the function pointer of the slot, and will not need moc introspection anymore. (It still needs it for the signal) But what we can also do is connecting to any function or functor.

Using the QTimer class

Let's take a minute to review the behavior that we defined for our finished app. The app has a button that, when clicked, changes the traffic signal from red to green. The button also starts a countdown timer, which is indicated visually in the text area of the UI. When the timer reaches 0, the traffic light changes to yellow, pauses briefly, and then changes to red.

We need a way to keep track of how much time is left before the traffic light should change to yellow. Fortunately, the Qt framework includes a class called QTimer that we can use to do just that. You can set a timer interval for a QTimer object and a signal, timeout(), will be emitted at that interval. For example, if you set an interval of 2000 milliseconds, the QTimer object emits its timeout() signal every two seconds while the timer is active. You can call start() to start the timer, and stop() to stop it.

We can use the functionality of QTimer in our traffic light app. We can use one QTimer object, with an interval of one second, to keep track of the countdown until the traffic light should turn yellow. When this QTimer emits its timeout() signal, we update the text in the countdown TextArea. We can use a second QTimer object, with an interval of about two seconds, to pause the traffic light in the yellow state before changing to the red state.

There's a problem with this plan, though: we can't use the QTimer class (and other Qt and C++ classes) in QML automatically. We need a way to provide access to the features of QTimer directly from QML. There are several ways to do this, but here are two possible approaches that we could choose to use in our app:

  • Use the attachedObjects list in a QML control to specify the C++ objects that you want to use (in this case, QTimer).
  • Create a class that extends the CustomControl class, and provide access to an underlying QTimer object. Then, register this new class for use in QML.

To demonstrate more Cascades features in this tutorial, we'll use the second approach for our traffic light app. One of the benefits of extending CustomControl is the ability to create a visual representation for the new control. Because CustomControl inherits from Control (which itself inherits from VisualNode), you can use the properties of these inherited classes to define how your control looks (for example, preferredWidth, opacity, scaleX, and so on). For the purposes of this tutorial, we won't create a visual representation for the timer that we make, but we'll leave that as an optional extension to our app.

Create the header file for the Timer class

To declare our class elements, create a C++ header file called timer.hpp in the src folder of the project (right-click the src folder and click New > Header File). In this file, keep the pre-populated code, and in between the #define and #endif statements, add the appropriate #include statements. We need to include both QObject and CustomControl. We also need to use a forward declaration of the QTimer class:

Next, we create the Timer class, extending CustomControl. We also use the Q_OBJECT macro to indicate that this class should be preprocessed by the Meta-Object Compiler (moc) tool to compile correctly. For more information about the moc tool in Qt, see Using the Meta-Object Compiler (moc) on the Qt website.

The QTimer class includes a couple of properties that we want to expose in our own Timer class. The active property indicates whether the timer is running, and the interval property specifies the current interval that the timeout() signals are emitted at. We expose these properties by using the Q_PROPERTY macro, and we use the READ and WRITE keywords inside this macro to specify functions that access and change each property. The NOTIFY keyword is also important, and specifies the signal that's emitted when the property changes. For more information about properties in Qt and the Q_PROPERTY macro, see The Property System on the Qt website.

We now declare the public functions of the Timer class, including the constructor. We need functions to get and set the interval of the timer, and we should also have a way to access the state of the timer (active or inactive):

This class includes two slots, start() and stop(), to start and stop the timer. Remember that slots are normal member functions, but are declared in a public slots: section so that they can be connected to signals if needed:

Our class also includes three signals: timeout(), intervalChanged(), and activeChanged(). These signals are emitted in the definitions of our class functions, which we'll add soon when we create our timer.cpp file. We declare our signals in a signals: section:

Finally, we declare the underlying QTimer object that our Timer class uses:

Create the source for the Timer class

To define our class elements, create a C++ source file called timer.cpp in the src folder of the project (right-click the src folder and click New > Source File). This source file doesn't include any pre-populated code, so we start by adding the appropriate #include statements. We need to include QTimer, as well as timer.hpp that we created:

Next, we create the constructor for Timer. The constructor creates a QTimer object to represent our timer. We also call QObject::connect() to connect the timeout() signal in QTimer to the timeout()signal of our Timer class. This way, when the QTimer emits the timeout() signal, our timer also emits its timeout() signal and we can handle it using a signal handler in QML. We use the setVisible() function to indicate that our timer shouldn't be visible on the screen, because it has no visual representation defined for it. The constructor also includes a Q_UNUSED macro, which simply means that the parent parameter isn't used in the body of the constructor.

The isActive() function just returns the value of the active property by calling isActive() of the underlying QTimer object. Similarly, the interval() function calls interval() of the QTimer object to return the interval of the timer:

The setInterval() function calls setInterval() of QTimer to set the interval of the timer, and also emits the intervalChanged() signal by using the emit keyword:

The last functions to implement are start() and stop(). These functions call the corresponding functions of the underlying QTimer object. They also emit the activeChanged() signal:

Our Timer class is now ready for us to use.

Home · All Classes · Modules

The QTimer class provides repetitive and single-shot timers.More...

Inherits QObject.

Methods

  • int interval (self)
  • bool isSingleShot (self)
  • setSingleShot (self, bool asingleShot)
  • start (self)
  • timerEvent (self, QTimerEvent)

Static Methods

  • singleShot (int msec, QObject receiver, SLOT()SLOT() member)

Qt5 Qtimer

Qt Signals

  • void timeout ()

Detailed Description

The QTimer class provides repetitive and single-shot timers.

The QTimer class provides a high-level programming interface fortimers. To use it, create a QTimer, connect its timeout() signal to the appropriateslots, and call start(). From thenon it will emit the timeout()signal at constant intervals.

Example for a one second (1000 millisecond) timer (from theAnalog Clock example):

From then on, the update() slot is called everysecond.

You can set a timer to time out only once by callingsetSingleShot(true). You can also use the static QTimer.singleShot() function to calla slot after a specified interval:

In multithreaded applications, you can use QTimer in any threadthat has an event loop. To start an event loop from a non-GUIthread, use QThread.exec(). Qtuses the timer's thread affinityto determine which thread will emit the timeout() signal. Because of this, youmust start and stop the timer in its thread; it is not possible tostart a timer from another thread.

As a special case, a QTimer with a timeout of 0 will time out assoon as all the events in the window system's event queue have beenprocessed. This can be used to do heavy work while providing asnappy user interface:

processOneThing() will from then on be calledrepeatedly. It should be written in such a way that it alwaysreturns quickly (typically after processing one data item) so thatQt can deliver events to widgets and stop the timer as soon as ithas done all its work. This is the traditional way of implementingheavy work in GUI applications; multithreading is now becomingavailable on more and more platforms, and we expect thatzero-millisecond QTimers will gradually be replaced by QThreads.

Accuracy and Timer Resolution

Timers will never time out earlier than the specified timeoutvalue and they are not guaranteed to time out at the exact valuespecified. In many situations, they may time out late by a periodof time that depends on the accuracy of the system timers.

The accuracy of timers depends on the underlying operatingsystem and hardware. Most platforms support a resolution of 1millisecond, though the accuracy of the timer will not equal thisresolution in many real-world situations.

Qtimer Signal Slot Examples

If Qt is unable to deliver the requested number of timer clicks,it will silently discard some.

Alternatives to QTimer

An alternative to using QTimer is to call QObject.startTimer() for your objectand reimplement the QObject.timerEvent() event handlerin your class (which must inherit QObject). The disadvantage is that timerEvent() does not support suchhigh-level features as single-shot timers or signals.

Another alternative to using QTimer is to use QBasicTimer. It is typically less cumbersomethan using QObject.startTimer() directly. SeeTimers for an overview of all threeapproaches.

Some operating systems limit the number of timers that may beused; Qt tries to work around these limitations.

Example

Method Documentation

Qtimer

QTimer.__init__ (self, QObjectparent = None)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Constructs a timer with the given parent.

Qtimer

int QTimer.interval (self)

bool QTimer.isActive (self)

bool QTimer.isSingleShot (self)

QTimer.setInterval (self, int msec)

QTimer.setSingleShot (self, bool asingleShot)

Qt Qtimer Example

QTimer.singleShot (int msec, QObjectreceiver, SLOT()SLOT() member)

This static function calls a slot after a given timeinterval.

It is very convenient to use this function because you do notneed to bother with a timerEvent or create a local QTimer object.

Example:

This sample program automatically terminates after 10 minutes(600,000 milliseconds).

The receiver is the receiving object and themember is the slot. The time interval is msecmilliseconds.

Note: This function is reentrant.

See alsosetSingleShot() and start().

QTimer.singleShot (int msec, callable receiver)

QTimer.start (self, int msec)

If the timer is already running, it will be stopped and restarted.

If singleShot is true,the timer will be activated only once.

QTimer.start (self)

This function overloads start().

Qtimer Timeout

Starts or restarts the timer with the timeout specified ininterval.

If the timer is already running, it will be stopped and restarted.

If singleShot is true,the timer will be activated only once.

Qtimer Update Ui

QTimer.stop (self)

Qtimer

See alsostart().

QTimer.timerEvent (self, QTimerEvent)

Reimplemented from QObject.timerEvent().

int QTimer.timerId (self)

Qt Signal Documentation

void timeout ()

See alsointerval, start(), and stop().

PyQt 4.11.4 for X11Copyright © Riverbank Computing Ltd and The Qt Company 2015Qt 4.8.7