Skip to content

07-advanced-connections/main.cpp

An example of how to use the KDBindings::Signal::connect() overloaded function for advanced slot connections.

The output of this example is:

1
2
3
Hello World!
Emitted value: 5
true
 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
  This file is part of KDBindings.

  SPDX-FileCopyrightText: 2021 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Author: Leon Matthes <leon.matthes@kdab.com>

  SPDX-License-Identifier: MIT

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

#include <ios>
#include <kdbindings/signal.h>

#include <iostream>
#include <string>

using namespace KDBindings;

void display()
{
    std::cout << "Hello World!" << std::endl;
}

void displayLabelled(const std::string &label, int value)
{
    std::cout << label << ": " << value << std::endl;
}

class SignalHandler
{
public:
    bool received = 0;

    void receive()
    {
        received = true;
    }
};

int main()
{
    Signal<int> signal;

    // Signal::connect allows connecting functions that take too few arguments.
    signal.connect(display);

    // As well as functions with too many arguments, as long as default values are provided.
    signal.connect(displayLabelled, "Emitted value");

    // This is very useful to connect member functions, where the first implicit argument
    // is a pointer to the "this" object.
    SignalHandler handler;
    signal.connect(&SignalHandler::receive, &handler);

    // This will print "Hello World!" and "Emitted value: 5" in an unspecified order.
    // It will also set handler.received to true
    signal.emit(5);

    std::cout << std::boolalpha << handler.received << std::endl;

    return 0;
}

Filename: 07-advanced-connections/main.cpp


Updated on 2024-03-19 at 00:03:31 +0000