Accessing Publish and Subscribe from QML

This examples shows how to access published context values from within QML. The example consists of two programs. The first, battery-publisher, is a standard Qt Widgets application to emulate a battery for the sole purpose of demonstrating the second program. It publishes the keys

 /power/battery/charge
 /power/battery/charging

and provides controls for modifying their values.

[Missing image battery-publisher.png]

The second program, battery-subscriber, is implemented in pure QML. It has the following features: A rectangular area representing the percent charge of the battery. It indicates a low battery state by changing the color to red, it is green otherwise. An animation is shown to indicate that the battery is being recharged.

[Missing image battery-subscriber.png]

Battery Subscriber

First, import the plugin library that provides the ValueSpaceSubscriber QML element.


Two ValueSpaceSubscriber instances are created, one for each of the battery values. We give each object a unique id so that we can reference it from elsewhere in the QML. We set the path properties to the Value Space path of the keys.


The default state of the rectangle used to visualize the battery charge uses the charge property of our BatteryCharge class in the expression for its height.


When the battery charge changes the height of the rectangle will automatically change.

Next we define two additional states. The low state is entered when the battery charge drops below 25% and the battery is not being recharged. When in this state the color is set to red.


The charging state is entered when the battery is being recharged. When in this state a particle effect animation is enabled.