Anslut logik till ditt QML användargränssnitt

Anslut bakgrundskod för att göra beräkningar och tillhandahålla användargränssnittet med data att visa

För att integrera logik i programmet behöver vi C++ bakgrundsklasser som kan utföra de viktiga beräkningarna. Att skriva logik i QML-filer avråds från, så försök att flytta så mycket som möjligt till bakgrundskoden, så att QML enbart används för att visa användargränssnittet, vilket är vad det är bäst på.

Skapa två nya filer som heter backend.cpp och backend.h för din nya bakgrundsklass. Glöm inte bort att lägga till den nya cpp-filen för den körbara filen i src/CMakeLists.txt, intill main.cpp.

Add the following content to the new header file (backend.h):

#pragma once

#include <QObject>

class Backend : public QObject
{
    Q_OBJECT

public:
    explicit Backend(QObject *parent = nullptr);
};

The backend.cpp file containing the definitions is similarly empty right now, it should contain something like the following:

#include "backend.h"

Backend::Backend(QObject *parent)
    : QObject(parent)
{

}

För närvarande känner inte användargränssnittet till din bakgrundsklass. För att ändra det måste vi registrera den nya typen i main.cpp. Bakgrundskoden skapas som en singleton, vilket betyder att den bara skapas en gång och existerar hela tiden från programmet startas till det stängs.

Right after creating the QQmlApplicationEngine , add the type registration to main.cpp as follows:

    Backend backend;
    qmlRegisterSingletonInstance<Backend>("org.kde.example", 1, 0, "Backend", &backend);

Glöm inte att inkludera den nya deklarationsfilen längst upp i main.cpp.

From now on, the backend will be known to QML as Backend. It is contained in a module called org.kde.example. Since the module is part of the application, you don't need to worry about versioning it, just stay with 1.0 and use it consistently throughout the application.

Importera den nya modulen i main.qml:

import org.kde.example 1.0

Nu har vi anslutit klassen som innehåller den framtida programlogiken, men den gör inte ännu någonting. För att ändra det, låt oss lägga till en egenskap i klassen. Egenskaper är mycket mer än en enkel variabel. De kan informera användargränssnittet om ändringar så att det kan uppdatera riktiga områden.

Right under the Q_OBJECT macro, add a new Q_PROPERTY .

Q_PROPERTY(QString introductionText READ introductionText WRITE setIntroductionText NOTIFY introductionTextChanged)

This may seem like a lot of code to just read and write some code from the backend. However, a closer look reveals that reading the property from the UI can already run some logic—same when it is written to. In this case, it will automatically inform the frontend and backend of changes.

The reading and writing is based on the concept of getter and setter functions. Go ahead and add a new private attribute to your class that holds the data, as well as the relevant getter and setter functions.

private:
    QString m_introductionText = "Hello World!";

Lägg till följande i den öppna sektionen

public:
    QString introductionText() const;
    void setIntroductionText(const QString &introductionText);
    Q_SIGNAL void introductionTextChanged();

The first function is the getter, the second the setter, and the third a signal that is emitted when the property is changed. The signal doesn't need any implementation in backend.cpp file, since it doesn't do much more than being emitted, but the getter and setter need to be implemented similar to the following:

QString Backend::introductionText() const
{
    return m_introductionText;
}

void Backend::setIntroductionText(const QString &introductionText)
{
    m_introductionText = introductionText;
    Q_EMIT introductionTextChanged();
}

Som du kan se, när tilldelningsfunktionen anropas, skickas signalen, och informerar användargränssnittet och bakgrundskoden om ändringen.

To display the text, add a heading to main.qml under the title property of the Kirigami.Page element already contained in the template.

Den resulterande koden i den delen av filen ska se ut så här:

...
Kirigami.Page {
    title: i18n("develop.kde.org tutorial")

    Kirigami.Heading {
        anchors.centerIn: parent
        text: Backend.introductionText
    }

    actions {
        main: Kirigami.Action {
            ...
        }
    }
}

Kompilera och starta nu programmet igen.

Gratulerar, du har lärt dig:

  • Hur man registrerar gränssnittstyper i QML
  • Att lägga till nya element i QML-filen
  • Att skapa nya QObject delklasser
  • Hur man lägger till egenskaper och vad de gör
  • Vad signaler är

Om du vill veta mer om integreringen mellan QML och C++, rekommenderar vi att läsa den officiella Qt-dokumentationen.