Evgenii Legotckoi
Nov. 4, 2019, 4:15 p.m.

QML - Tutorial 036. Working with Signals and Slots in QML

This article is the most comprehensive description of signals and slots in QML compared to all previous articles on this site.

In this article, I will try to explain the following when working with Qt/QML + Qt/C++:

  • ways to declare signals and slots, also called methods in the C ++ class, which will be registered in the QML layer
  • ways to connect to signals of classes declared in C ++ as context
  • work with Q_PROPERTY, which also requires signals and slots
  • ways to connect signals and slots in QML
  • etc.

Signals and slots from the C++ class

Let's create our first class that will work with signals and slots in QML. This is one of the very first examples that I have already shown, but I will repeat this example so that the article is as complete as possible.

In this example, I want to create an application that has one button and by pressing this button increases the counter that is inside the C++ class. This C++ class will be registered as a context property in the QML engine of our application.

App appearance will be next

AppCore.h

Declaring signals and slots in C ++ code will not differ much from the classical Qt/C++.

  1. #ifndef APPCORE_H
  2. #define APPCORE_H
  3.  
  4. #include <QObject>
  5.  
  6.  
  7. class AppCore : public QObject
  8. {
  9. Q_OBJECT
  10. public:
  11. explicit AppCore(QObject *parent = nullptr);
  12.  
  13. signals:
  14. void sendToQml(int count);
  15.  
  16. public slots:
  17. void receiveFromQml();
  18.  
  19. private:
  20. int m_counter {0};
  21. };
  22.  
  23. #endif // APPCORE_H
  24.  

AppCore.cpp

As well as the implementation of the methods themselves.

  1. #include "AppCore.h"
  2.  
  3. AppCore::AppCore(QObject* parent) : QObject(parent)
  4. {
  5. }
  6.  
  7. void AppCore::receiveFromQml()
  8. {
  9. // We increase the counter and send a signal with its value
  10. ++m_counter;
  11. emit sendToQml(m_counter);
  12. }
  13.  

main.cpp

  1. #include <QGuiApplication>
  2. #include <QQmlApplicationEngine>
  3. #include <QQmlContext>
  4. #include "AppCore.h"
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8. QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  9.  
  10. QGuiApplication app(argc, argv);
  11.  
  12. AppCore appCore; // Create the application core with signals and slots
  13.  
  14. QQmlApplicationEngine engine;
  15. QQmlContext *context = engine.rootContext();
  16.  
  17. /* We load the object into the context to establish the connection,
  18.      * and also define the name "appCore" by which the connection will occur
  19. * */
  20. context->setContextProperty("appCore", &appCore);
  21.  
  22. const QUrl url(QStringLiteral("qrc:/main.qml"));
  23. QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
  24. &app, [url](QObject *obj, const QUrl &objUrl) {
  25. if (!obj && url == objUrl)
  26. QCoreApplication::exit(-1);
  27. }, Qt::QueuedConnection);
  28. engine.load(url);
  29.  
  30. return app.exec();
  31. }
  32.  

main.qml

And now the most interesting. How to use an object loaded in a QML context and how to connect to its signals.

As you remember, we loaded the object into the context QML under the name appCore , we will use this object to access it. But to connect to the signal, we will need to use the QML type Connections .

  1. import QtQuick 2.12
  2. import QtQuick.Controls 2.12
  3. import QtQuick.Window 2.12
  4.  
  5. Window {
  6. visible: true
  7. width: 640
  8. height: 480
  9. title: qsTr("QML Signals and Slots")
  10.  
  11. /* Using the Connections Object
  12.      * Establish a connection with the application core object
  13.      * */
  14. Connections {
  15. target: appCore // Specify the target to connect
  16.         /* Declare and implement the function as a parameter
  17.          * object and with a name similar to the name of the signal
  18.          * The difference is that we add on at the beginning and then write
  19.          * capitalized
  20.          * */
  21. onSendToQml: {
  22. labelCount.text = count // Set the counter to the text label
  23. }
  24. }
  25.  
  26.  
  27. Label {
  28. id: labelCount
  29. text: "0"
  30.  
  31. anchors.bottom: parent.verticalCenter
  32. anchors.horizontalCenter: parent.horizontalCenter
  33. anchors.bottomMargin: 15
  34. }
  35.  
  36. Button {
  37. text: qsTr("Increase counter")
  38. onClicked: appCore.receiveFromQml() // Вызов слота
  39.  
  40. anchors.top: parent.verticalCenter
  41. anchors.horizontalCenter: parent.horizontalCenter
  42. }
  43. }
  44.  

Thus, you can access the object that was loaded into the context of the QML engine, call its slot, and process the signal from this object.

It is also not necessary to declare receiveFromQml() as a slot in this case. This method can also be declared as Q_INVOKABLE method.

  1. public:
  2. explicit AppCore(QObject *parent = nullptr);
  3. Q_INVOKABLE void receiveFromQml();

Using Q_PROPERTY

The next option is to use the Q_PROPERTY macro. A classic property in Qt might look like this for our task

  1. Q_PROPERTY(int counter READ counter WRITE setCounter NOTIFY counterChanged)

This property has the following components:

  • type of property, as well as its name: int counter , which are bound to the variable int m_counter inside the class, this is the logic of code generation in Qt
  • name of the method to read, matches the name of the property: counter
  • method name for setting the value: setCounter
  • signal that reports property changes: counterChanged

You can also pass additional parameters to this macro, but this is beyond the scope of this article. And also the property can be read only, that is, without a setter.

Now look at the full code using Q_PROPERTY

AppCore.h

  1. #ifndef APPCORE_H
  2. #define APPCORE_H
  3.  
  4. #include <QObject>
  5.  
  6.  
  7. class AppCore : public QObject
  8. {
  9. Q_OBJECT
  10. public:
  11. Q_PROPERTY(int counter READ counter WRITE setCounter NOTIFY counterChanged)
  12. explicit AppCore(QObject *parent = nullptr);
  13.  
  14. int counter() const;
  15.  
  16. public slots:
  17. void setCounter(int counter);
  18.  
  19. signals:
  20. void counterChanged(int counter);
  21.  
  22. private:
  23. int m_counter {0};
  24. };
  25.  
  26. #endif // APPCORE_H
  27.  

AppCore.cpp

  1. #include "AppCore.h"
  2.  
  3. AppCore::AppCore(QObject* parent) : QObject(parent)
  4. {
  5.  
  6. }
  7.  
  8. int AppCore::counter() const
  9. {
  10. return m_counter;
  11. }
  12.  
  13. void AppCore::setCounter(int counter)
  14. {
  15. if (m_counter == counter)
  16. return;
  17.  
  18. m_counter = counter;
  19. emit counterChanged(m_counter);
  20. }
  21.  

main.qml

Here you will see that connecting the property and accessing it has become easier thanks to the declarative style of QML code. Of course, you cannot always use properties, sometimes you just need to use signals, slots, and Q_INVOKABLE methods. But for variables like counter, properties are likely to be much more convenient.

  1. import QtQuick 2.12
  2. import QtQuick.Controls 2.12
  3. import QtQuick.Window 2.12
  4.  
  5. Window {
  6. visible: true
  7. width: 640
  8. height: 480
  9. title: qsTr("QML Signals and Slots")
  10.  
  11. Label {
  12. id: labelCount
  13. text: appCore.counter
  14.  
  15. anchors.bottom: parent.verticalCenter
  16. anchors.horizontalCenter: parent.horizontalCenter
  17. anchors.bottomMargin: 15
  18. }
  19.  
  20. Button {
  21. text: qsTr("Increase counter")
  22. onClicked: ++appCore.counter
  23.  
  24. anchors.top: parent.verticalCenter
  25. anchors.horizontalCenter: parent.horizontalCenter
  26. }
  27. }
  28.  

Connecting signals inside QML files

Now consider the option of connecting signals and slots (functions) inside QML files. There will no longer be any C ++ code.

  1. import QtQuick 2.12
  2. import QtQuick.Controls 2.12
  3. import QtQuick.Window 2.12
  4.  
  5. Window {
  6. id: mainWindow
  7. visible: true
  8. width: 640
  9. height: 480
  10. title: qsTr("QML Signals and Slots")
  11.  
  12. // Counter property
  13. property int counter: 0
  14.  
  15. // Method for counter manipulation
  16. function inrementCounter()
  17. {
  18. ++counter;
  19. }
  20.  
  21. Label {
  22. id: labelCount
  23. text: mainWindow.counter
  24.  
  25. anchors.bottom: parent.verticalCenter
  26. anchors.horizontalCenter: parent.horizontalCenter
  27. anchors.bottomMargin: 15
  28. }
  29.  
  30. Button {
  31. id: button
  32. text: qsTr("Increase counter")
  33.  
  34. anchors.top: parent.verticalCenter
  35. anchors.horizontalCenter: parent.horizontalCenter
  36.  
  37. Component.onCompleted: {
  38. // When the button is created, then connect the click signal on the button
  39.             // to the method for increasing the counter in the application window
  40. button.clicked.connect(mainWindow.inrementCounter)
  41. }
  42. }
  43. }
  44.  

Among other things, you can use and disable signals from slots

  1. button.clicked.disconnect(mainWindow.inrementCounter)

Connect a signal to a signal

Also in QML there is still the ability to connect a signal to a signal, as in Qt/C++. Look at the following artificial example.

  1. import QtQuick 2.12
  2. import QtQuick.Controls 2.12
  3. import QtQuick.Window 2.12
  4.  
  5. Window {
  6. id: mainWindow
  7. visible: true
  8. width: 640
  9. height: 480
  10. title: qsTr("QML Signals and Slots")
  11.  
  12. // Announcing a button click signal in the application window
  13. signal buttonClicked;
  14.  
  15. Label {
  16. id: labelCount
  17. text: counter
  18.  
  19. anchors.bottom: parent.verticalCenter
  20. anchors.horizontalCenter: parent.horizontalCenter
  21. anchors.bottomMargin: 15
  22.  
  23. // Counter property
  24. property int counter: 0
  25.  
  26. // Method for counter manipulation
  27. function inrementCounter()
  28. {
  29. ++counter;
  30. }
  31. }
  32.  
  33. Button {
  34. id: button
  35. text: qsTr("Increase counter")
  36.  
  37. anchors.top: parent.verticalCenter
  38. anchors.horizontalCenter: parent.horizontalCenter
  39.  
  40. Component.onCompleted: {
  41. // When the button is created, then connect the click signal on the button
  42.             // to the method for increasing the counter in the application window
  43. button.clicked.connect(mainWindow.buttonClicked)
  44. }
  45. }
  46.  
  47. Component.onCompleted: {
  48. buttonClicked.connect(labelCount.inrementCounter)
  49. }
  50. }
  51.  

In this case, the counter will continue to increase when the button is pressed. But the button press signal is not connected directly to the counter increase function, but is forwarded through the signal.

Using Variables in Signals

QML also has the ability to use variables in signals.

  1. import QtQuick 2.12
  2. import QtQuick.Controls 2.12
  3. import QtQuick.Window 2.12
  4.  
  5. Window {
  6. id: mainWindow
  7. visible: true
  8. width: 640
  9. height: 480
  10. title: qsTr("QML Signals and Slots")
  11.  
  12. // Signal with argument
  13. signal setCounter(var number);
  14.  
  15. Label {
  16. id: labelCount
  17. text: counter
  18.  
  19. anchors.bottom: parent.verticalCenter
  20. anchors.horizontalCenter: parent.horizontalCenter
  21. anchors.bottomMargin: 15
  22.  
  23. // Counter property
  24. property int counter: 0
  25.  
  26. // Method for counter manipulation, takes an argument
  27. function setCounter(number)
  28. {
  29. counter = number;
  30. }
  31. }
  32.  
  33. Button {
  34. id: button
  35. text: qsTr("Increase counter")
  36.  
  37. anchors.top: parent.verticalCenter
  38. anchors.horizontalCenter: parent.horizontalCenter
  39.  
  40. onClicked: {
  41. // We call the signal of the application window for installing the counter indicating the new counter value
  42. mainWindow.setCounter(labelCount.counter + 1)
  43. }
  44. }
  45.  
  46. Component.onCompleted: {
  47. setCounter.connect(labelCount.setCounter)
  48. }
  49. }
  50.  

Conclusion

For the most part, this entire article fits into several points:

  • In C ++, to interact with the QML layer, you can use signals, slots, Q_INVOKABLE methods, as well as create properties using the Q_PROPERTY macro
  • In order to respond to signals from objects, you can use the QML type Connections
  • Q_PROPERTY obeys the declarative style of QML and, when a property is changed, it can automatically set new values, if the property has been added to any object in QML. In this case, the signal slot connections are set automatically.
  • In QML, you can connect and disconnect signal / slot connections using the following syntax:
    • object1.signal.connect (object2.slot)
    • object1.signal.disconnect (object2.slot)
  • Signals in QML can also be connected to other signals, as is done in Qt / C ++
  • Signals in QML may also have arguments

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html