Skip to content

06-lazy-property-bindings/main.cpp

An example of how to use KDBindings::BindingEvaluator together with a KDBindings::Property to create a Property binding that is only reevaluated on demand.

The output of this example is:

1
2
The initial size of the image = 1920000 bytes
The new size of the image = 8294400 bytes

Note the difference to 05-property-bindings/main.cpp, where the new size of the image is calculated twice.

This feature is especially useful to reduce the performance impact of bindings and to create bindings that only update in specific intervals.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
  This file is part of KDBindings.

  SPDX-FileCopyrightText: 2021-2022 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Author: Sean Harmer <sean.harmer@kdab.com>

  SPDX-License-Identifier: MIT

  Contact KDAB at <info@kdab.com> for commercial licensing options.
*/

#include <kdbindings/binding.h>
#include <kdbindings/property.h>
#include <kdbindings/signal.h>

#include <iostream>

using namespace KDBindings;

static BindingEvaluator evaluator;

class Image
{
public:
    const int bytesPerPixel = 4;
    Property<int> width{ 800 };
    Property<int> height{ 600 };
    const Property<int> byteSize = makeBoundProperty(evaluator, 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;

    evaluator.evaluateAll();

    return 0;
}

Filename: 06-lazy-property-bindings/main.cpp


Updated on 2022-04-12 at 00:03:57 +0000

Back to top