Book Image

QT5 Blueprints

By : Symeon Huang
Book Image

QT5 Blueprints

By: Symeon Huang

Overview of this book

Table of Contents (17 chapters)
Qt 5 Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Connecting two signals


Due to the weak couplings of the Qt signals and slot mechanisms, it is viable to bind signals to each other. It may sound confusing, so let me draw a diagram to make it clear:

When an event triggers a specific signal, this emitted signal could be another event, which will emit another specific signal. It is not a very common practice, but it tends to be useful when you deal with some complex signals and slot connection networks, especially when tons of events lead to the emission of only a few signals. Although it definitely increases the complexity of the project, binding these signals could simplify the code a lot. Append the following statement to the construction function of MainWindow:

connect(ui->bonjourButton, &QPushButton::clicked, ui->helloButton, &QPushButton::clicked);

You'll get two lines in a plain text edit after you click on the Bonjour button. The first line is Bonjour and the second one is Hello. Apparently, this is because we coupled the clicked signal of the Bonjour button with the clicked signal of the Hello button. The clicked signal of the latter has already been coupled with a slot, which results in the new text line, Hello. In fact, it has the same effect as the following statement:

connect(ui->bonjourButton, &QPushButton::clicked, [this](){
    emit ui->helloButton->clicked();
});

Basically, connecting two signals is a simplified version of connecting a signal and a slot, while the slot is meant to emit another signal. As for priority, the slot(s) of the latter signal will be handled when the event loop is returned to the object.

However, it is impossible to connect two slots because the mechanism requires a signal while a slot is considered a receiver instead of a sender. Therefore, if you want to simplify the connection, just wrap these slots as one slot, which can be used for connections.