Introducing KDBindings Reactive Programming and Data Binding in C++
All Qt developers should know about signals, slots, and properties. Those of you who have used QML will know that property bindings are super useful and cool. Bindings allow us to write more reactive and declarative style code. However, they are only available within QML, which means there are no compile time errors when you do something wrong.
Wouldn’t it be nice if we could have the sunlit uplands of Brexit — erm, I mean bindings — from the comfort and speed of C++? Wouldn’t it be nice if you could use this with or without Qt? Wouldn’t it be nice if this was just plain C++ with no moc required? Wouldn’t it be nice if you could avoid executing a binding many times when you update each dependent property (lazy/deferred evaluation)? Wouldn’t it be nice if you could have this right now?
Well, you can! Read on to find out more details. For those of you who can’t wait, you can grab the code and start using it right now from GitHub.
How C++ Bindings Look in Use
Here is a simple but complete example to give you a taste of what using properties and bindings in C++ looks like:
#include "kdbindings/binding.h"
#include "kdbindings/property.h"
#include "kdbindings/signal.h"
#include <iostream>
using namespace KDBindings;
class Image
{
public:
const int bytesPerPixel = 4;
Property<int> width { 800 };
Property<int> height { 600 };
const Property<int> byteSize = makeBoundProperty(bytesPerPixel * width * height);
};
int main()
{
Image img;
std::cout << "The initial size of the image = "
<< img.byteSize.get() << " bytes" << std::endl;
img.byteSize.valueChanged().connect([] (const int &newValue) {
std::cout << "The new size of the image = " << newValue << " bytes" << std::endl;
});
img.width = 1920;
img.height = 1080;
return 0;
}
The Image
class declares 3 properties, all containing an integer. The first two, width
and height
, are simply initialized to values. The third property, byteSize
, is initialized to whatever is returned from the makeBoundProperty()
function. We will go into this in full and gory detail later. This, however, is how we create an immediate-mode property binding — that is, a binding that gets evaluated immediately when any of it’s dependent properties change. In this case, that means if width
or height
changes, then byteSize
will get a new value. Pretty easy and natural, isn’t it? And we don’t have to worry about the mechanics of connecting to changed signals; that is all taken care of for us.
The main function simply instantiates an Image object and prints out the initial value of the byteSize
property. We use the get()
function to extract the contained value here but we do provide an overloaded stream operator to do this for us too.
On line 24, we create a lambda “slot” and connect it to the valueChanged()
signal of the byteSize
property so that we print out the new image size whenever it changes. This syntax, although slightly different from Qt’s, should be familiar enough to pick up and use. The reason we can do this here is because in this implementation a signal is itself an object rather than just a function on a QObject
.
Lines 28 and 29 both alter the other properties of the image. Each of these causes the binding expression to be re-evaluated. We will show later how to avoid this and have the bindings evaluated lazily. The complete output from running this simple example is:
The initial size of the image = 1920000 bytes
The new size of the image = 4608000 bytes
The new size of the image = 8294400 bytes
Lazy Property Bindings
One of the issues with property bindings in Qt5/QML is that they are evaluated as soon as any of the properties on which they depend are changed. If you are updating a lot of properties, this can lead to a huge amount of wasted CPU time spent evaluating a binding that will be invalidated the next time you change a dependent property. Well, we can avoid this completely by introducing the concept of a BindingEvaluator
.
To make use of lazily evaluated property bindings, all you need to do is to pass in a BindingEvaluator
as the first argument to the makeBinding()
function:
static BindingEvaluator evaluator;
...
const Property<int> byteSize = makeBoundProperty(evaluator, bytesPerPixel * width * height);
With the binding associated to an evaluator, it is now lazily evaluated. No matter how many dependent input properties you change, the binding is only evaluated when you request it:
img.width = 1920; // Does not trigger an evaluation of the binding
img.height = 1080; // Nor does this
evaluator.evaluateAll(); // This does!
With the above changes to our example, the output now becomes:
The initial size of the image = 1920000 bytes
The new size of the image = 8294400 bytes
And you can see we have saved the pointless evaluation of the binding when we change the image width knowing that we will then immediately change the image height, too.
This gives us a lot more control over bindings than is possible in QML and allows us to save precious CPU time/battery power!
It gets better, though. With the evaluator concept, we can go even further:
- You could group bindings into logical sets based upon their purpose, e.g., all the bindings from subsystem A use this evaluator and all the bindings from subsystem B use a different evaluator. Triggering evaluator A before B means you can be sure that all the state in subsystem A is consistent before you move on to subsystem B’s bindings.
- Building upon the first point, we can also control the frequency at which we update property bindings. For example, we may want all the bindings in the back-end data layer to be updated at full frequency (once per simulation loop). However, if you want to attach to your simulation a GUI that is not an unreadable strobe of flashing numbers, you could elect to update the bindings related to GUI code only once every 0.5s, say.
The choice is yours. This library only provides the facility; what you choose to do with this lazy evaluation is entirely up to you!
Actually, the immediate mode bindings also use an evaluator behind-the-scenes. It’s just a dummy one, though, and we ignore it. We just kick off an evaluation as soon as we see the expression is dirty, via a signal.
What We Can Do in a Property Binding
Thus far, we have only seen a trivial example of a property binding. This sufficed to show how to use bindings, but it’s not particularly compelling if all we can use is a multiply operation. So what else can we put into property bindings? Well, pretty much anything is the answer.
- The usual unary operators (+, -, !, ~)
- Binary operators (+, -, *, /, %, etc)
- Normal values
- Property values
- Functions
This means you can do more interesting things inside your property bindings, such as:
BindingEvaluator evaluator;
Property<int> a { 2 };
Property<int> b { 7 };
Property<int> c { 3 };
Property<int> d { 4 };
auto e = makeBoundProperty(evaluator, (a + b) * (c + d)); // e is a Property<int> too.
Property<float> x { -7.5f };
Property<float> y { 2.35f };
auto z = makeBoundProperty(evaluator, y + abs(sin(x)));
“That’s cool, uh-huh. But I’ve got this other custom function I want to use in a binding…” No problem! It’s easy to expose your own functions for use with bindings. Here’s how:
struct node_paraboloid
{
template <typename T>
auto operator()(T&& x, T&& y) const // Use as many arguments as you like
{
// Do something useful or call a library function...
return x * x + y * y;
}
};
KDBINDINGS_DECLARE_FUNCTION(paraboloid, node_paraboloid {})
auto evaluator = BindingEvaluator{};
Property<int> x { -2 };
Property<int> y { 3 };
auto z = makeBoundProperty(evaluator, paraboloid(x, y));
Pretty neat, eh? And as the comments say, we can use any number of function arguments, thanks to the wonders of variadic templates. This means that we can put pretty much anything into a binding expression. It’s quite neat how this works behind-the-scenes with compile time building of the dependency tree — but I’ll save that for a deep-dive in a follow-up post.
Broken Bindings
Anyone who has used property bindings in QML will know just how much of a pain in the posterior broken bindings can be. Easy to do by mistake and can be annoyingly difficult to track down! Never fear! Thanks to C++ and a bit of design work, we can help eliminate the curse of broken bindings!
Compile-time Prevention
Just mark the property with a binding as const and this will stop you from assigning another binding or value to it at compile time.
Property<int> a { 10 };
Property<int> b { 14 };
const Property<int> x = makeBoundProperty(defaultEvaluator(), 2 * (a + b));
...
x = 35; // Compile-time error!
Run-time prevention
If for whatever reason you can’t mark your property as const, e.g., if you want to switch it between two different bindings depending upon a mode, then you can still prevent accidentally assigning a value to the property:
Property<int> a { 10 };
Property<int> b { 14 };
Property<int> x = makeBoundProperty(defaultEvaluator(), 2 * (a + b));
...
x = 35; // Throws a ReadOnlyProperty exception
The KDBindings project allows us to have:
- Signals and slots with support for missing/default arguments.
- Properties templated on the contained type.
- Use of signals and properties anywhere. No need for
QObject
ormoc
. - Property bindings allowing reactive code to be written without having to do all the low-level, error-prone plumbing by hand.
- Plain C++! Yay for compile time errors, const correctness, more efficiency, debugging!
- Lazy evaluation of property bindings!
- No more broken bindings (hopefully)!
- A totally stand-alone “header-only” library.
- Compatibility with any C++17 compiler.
- The option of use with Qt, if you so wish.
- Available now and MIT licensed!
In a follow-up post, we will take a look at some of the interesting inner workings of KDBindings.
Please feel free to take it for a test-drive and let us know what you think.
If you like this article and want to read similar material, consider subscribing via our RSS feed.
Subscribe to KDAB TV for similar informative short video content.
KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.
This is pretty fantastic, thanks!
Will take a while to put into production as it’s quite a paradigm shift, but big thanks for making this available.
Thank you. If you have used QML property bindings, this feels fairly similar but in the comfort of C++. We’ve been nicely surprised by how much boilerplate code you can eliminate in some situations.
Very cool work!
For that last example, it would be great to be able to set the size of the image, and have the earliest-changed value between width or height update to keep the system valid. What’s being described between width, height, and the size of the image is a relationship between all three. Thus it would be exceedingly useful to be able to modify any of those parameters, and the system tweak the other parameters as necessary to keep the relationship valid. It’s already working for mutating the width and height – now, how hard would it be to have all three mutable? For example, you could imagine an “image size” dialog box where you give the user the ability to change any of these parameters to fit their requirements (e.g., I want the image to be these dimensions, or I need a smaller image that can be no more than X bytes in size so I can e.g., send it over a network faster/preview/etc.)
Thank you. As mentioned on reddit, this would need n-way tracking of the relationships. It may be possible to do something nice around this idea though. We will have a think about it.
(Two years later…) I’m not sure bindings are the appropriate method of expressing such behavior. It would nearly always require some constraint logic that’s too complex to express via bindings.
For example, say you want to adjust the bytesize and have the width and height automatically updated. Well, how do you compute width and height from bytesize? Any bytesize you set, there are dozens of different width/height combinations that will produce that value. A naïve implementation can simply reduce width and height proportionally (preserving aspect ratio), but that’s rarely satisfactory. In typical situations, there will be additional constraints, like requiring width and/or height to be multiples of some base value (2, 4, 8, 16…). Even if you’ll accept any integer, there are questions like “how should the values be rounded?” that require code to answer them.
n-ways also complicate the update logic. If I have bytesize dependent on width and height, and width and height dependent on bytesize, then what should happen when I change the height? Should it update the bytesize, or adjust the width to keep the bytesize constant?
That kind of constraint and update logic requires code to implement it. To do it all with bindings, you’d also have to solve the circular-reference problem (like in Excel spreadsheets), where cascading updates turn into infinite loops. (QObject provides .blockSignals() specifically to prevent those cascades, when code is updating a value based on the value of other connected objects.)
That’s correct. An n-way solution is not easily possible without knowing more about specific constraints. In such cases you can use the signals to call your own functions to do as you wish. Bindings are not a perfect one-stop solution but they can be a nice syntactic sugar in many common situations. They are just another tool in your toolbox.