Evgenij LegotskojNov. 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++.

#ifndef APPCORE_H
#define APPCORE_H

#include <QObject>


class AppCore : public QObject
{
    Q_OBJECT
public:
    explicit AppCore(QObject *parent = nullptr);

signals:
    void sendToQml(int count);

public slots:
    void receiveFromQml();

private:
    int m_counter {0};
};

#endif // APPCORE_H

AppCore.cpp

As well as the implementation of the methods themselves.

#include "AppCore.h"

AppCore::AppCore(QObject* parent) : QObject(parent)
{
}

void AppCore::receiveFromQml()
{
    // We increase the counter and send a signal with its value
    ++m_counter;
    emit sendToQml(m_counter);
}

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "AppCore.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    AppCore appCore;    // Create the application core with signals and slots

    QQmlApplicationEngine engine;
    QQmlContext *context = engine.rootContext();

    /* We load the object into the context to establish the connection,
     * and also define the name "appCore" by which the connection will occur
     * */
    context->setContextProperty("appCore", &appCore);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

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 .

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("QML Signals and Slots")

    /* Using the Connections Object
     * Establish a connection with the application core object
     * */
    Connections {
        target: appCore // Specify the target to connect
        /* Declare and implement the function as a parameter
         * object and with a name similar to the name of the signal
         * The difference is that we add on at the beginning and then write
         * capitalized
         * */
        onSendToQml: {
            labelCount.text = count // Set the counter to the text label
        }
    }


    Label {
        id: labelCount
        text: "0"

        anchors.bottom: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottomMargin: 15
    }

    Button {
        text: qsTr("Increase counter")
        onClicked: appCore.receiveFromQml() // Вызов слота

        anchors.top: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
    }
}

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.

public:
    explicit AppCore(QObject *parent = nullptr);
    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

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

#ifndef APPCORE_H
#define APPCORE_H

#include <QObject>


class AppCore : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(int counter READ counter WRITE setCounter NOTIFY counterChanged)
    explicit AppCore(QObject *parent = nullptr);

    int counter() const;

public slots:
    void setCounter(int counter);

signals:
    void counterChanged(int counter);

private:
    int m_counter {0};
};

#endif // APPCORE_H

AppCore.cpp

#include "AppCore.h"

AppCore::AppCore(QObject* parent) : QObject(parent)
{

}

int AppCore::counter() const
{
    return m_counter;
}

void AppCore::setCounter(int counter)
{
    if (m_counter == counter)
        return;

    m_counter = counter;
    emit counterChanged(m_counter);
}

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.

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("QML Signals and Slots")

    Label {
        id: labelCount
        text: appCore.counter

        anchors.bottom: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottomMargin: 15
    }

    Button {
        text: qsTr("Increase counter")
        onClicked: ++appCore.counter

        anchors.top: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
    }
}

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.

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12

Window {
    id: mainWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("QML Signals and Slots")

    // Counter property
    property int counter: 0

    // Method for counter manipulation
    function inrementCounter()
    {
        ++counter;
    }

    Label {
        id: labelCount
        text: mainWindow.counter

        anchors.bottom: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottomMargin: 15
    }

    Button {
        id: button
        text: qsTr("Increase counter")

        anchors.top: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter

        Component.onCompleted: {
            // When the button is created, then connect the click signal on the button
            // to the method for increasing the counter in the application window
            button.clicked.connect(mainWindow.inrementCounter)
        }
    }
}

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

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.

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12

Window {
    id: mainWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("QML Signals and Slots")

    // Announcing a button click signal in the application window
    signal buttonClicked;

    Label {
        id: labelCount
        text: counter

        anchors.bottom: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottomMargin: 15

        // Counter property
        property int counter: 0

        // Method for counter manipulation
        function inrementCounter()
        {
            ++counter;
        }
    }

    Button {
        id: button
        text: qsTr("Increase counter")

        anchors.top: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter

        Component.onCompleted: {
            // When the button is created, then connect the click signal on the button
            // to the method for increasing the counter in the application window
            button.clicked.connect(mainWindow.buttonClicked)
        }
    }

    Component.onCompleted: {
        buttonClicked.connect(labelCount.inrementCounter)
    }
}

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.

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12

Window {
    id: mainWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("QML Signals and Slots")

    // Signal with argument
    signal setCounter(var number);

    Label {
        id: labelCount
        text: counter

        anchors.bottom: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottomMargin: 15

        // Counter property
        property int counter: 0

        // Method for counter manipulation, takes an argument
        function setCounter(number)
        {
            counter = number;
        }
    }

    Button {
        id: button
        text: qsTr("Increase counter")

        anchors.top: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter

        onClicked: {
            // We call the signal of the application window for installing the counter indicating the new counter value
            mainWindow.setCounter(labelCount.counter + 1)
        }
    }

    Component.onCompleted: {
        setCounter.connect(labelCount.setCounter)
    }
}

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
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Fornex

Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
V

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
DK

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
s
  • storm
  • Jan. 20, 2023, 10:30 p.m.

C++ - Тест 003. Условия и циклы

  • Result:0points,
  • Rating points-10
Popular publications in the last 90 Days
Last comments
S

Qt WinAPI - Lesson 004. QtIFW - Automation WinDeployQt and build installers with Qt Installer Framework

Hello Evgenij, regarding the online installer, I've tried many times to use web host for the created repo after repogen step. I tried using github but I found people talking it is not …
  • juvf
  • Jan. 17, 2023, 9:18 a.m.

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

PS. Почти дописал плеер на QML. Уперся в ограничения QML. Переписываю плеер на с++/qt, а графика останится в qml. Нашел то, что мне надо, а именно индикатор звука. Qt может перехватывать аудиопо…

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

В этом случае вижу только какой-нибудь костыль в стиле перебора по всем индексам в заголовке с помощью методу headerData . То есть пройтись в for цикле пока не будет совпадения н…
a
  • avt
  • Dec. 12, 2022, 8:06 p.m.

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Спасибо за ответ. Нет, дело не в читаемости кода, в разных таблицах у меня есть столбцы с одинаковым именем, но с разными индексами. Хотел сделать решение по имени столбца для всех таблиц сразу.…
  • juvf
  • Dec. 12, 2022, 3:06 p.m.

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

Спасибо.
Now discuss on the forum

Как создать уникальное значение поля на основе существующих значений

В принципе это можно сделать так: def unique_field(self): return '{0}_{1}'.format(self.title, self.price)class Tovar(models.Model): title=models.CharField('Наименование',max_length=…
W
  • Wayne
  • Jan. 27, 2023, 12:47 p.m.

Здравствуйте помогите с qml

как сделать так, чтобы зеленая фигура при движения за пределы круга пропадала на qml
AB

Sorting the added QML elements in the ListModel

I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

QSqlRelatipnalTabelModel Qt 4.8.1 как получить id внешней связи?

Наконец-то готовы представить полноценное развитие Qt QSqlTableModel и QTableView. Посмотреть можно у нас на сайте здесь На github здесь здесь Радостная новос…
P
  • Pisych
  • Jan. 25, 2023, 10:01 p.m.

Ввод бухгалтерского документа в одной форме

вопрос снят. спасибо за ответы. сообразил, как сделать:)
About
Services
© EVILEG 2015-2022
Recommend hosting TIMEWEB