Daniel
Daniel

Reputation: 11

How to mock the data that is taken from the QQmlEngine context (C++ code) to use Qt Design Studio?

I have a desktop application that is implemented in QML and C++. A large number of objects (data) I get from the QQmlEngine context, which I create in C++ and put there. The application also supports a dark and light theme. Almost all component colors are placed in a singleton style file, which checks which theme is currently installed. In the code, I provide only the basic principles of the application to understand the essence of the issue.

// main.cpp

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    qQmlEngine = new QQmlApplicationEngine(&app);

    MyCppObject object = new MyCppObject();

    qQmlEngine->rootContext()->setContextProperty("MyCppObject", object);
    qQmlEngine->rootContext()->setContextProperty("ThemeMode", "dark");
        const QUrl url(QStringLiteral("qrc:/qml/main.qml"));
    qQmlEngine->load(url);

    return app.exec();
}
// Style.qml

pragma Singleton

import QtQuick 2.15

QtObject {
    property string mode: ThemeMode
    property color backgroundColor: mode === "light" ? 'white' : 'black'
    property color textColor: mode === "light" ? 'black' : 'white'
}
import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    height: 320
    width: 240
    Rectangle {
        anchors.fill: parent
        color: Style.backgroundColor
        Text {
            text: MyCppObject.variable1
            color: Style.textColor
        }
        Text {
            text: MyCppObject.variable2
            color: Style.textColor
        }
    }

}

It is also often used to get lists of data by inheriting from QAbstractListModel.

class MyCppObject2 : public QAbstractListModel

ListView {
    model: MyCppObject2
    delegate: Item {
        Text {
            text: display.variable1
        }
        Text {
            text: display.variable2
        }
}

I would like a designer (who may not know QML and JavaScript) to be able to edit the user interface in Qt Design Studio without compiling the entire application.

For example, when editing the color of a component in Qt Design Studio, the color changes directly in the selected current component. Obviously, Qt Design Studio does not know anything about the fact that the colors are in Style.qml. In addition, we have a check by the ternary operator which theme is currently installed. What can be done about it?

mode === "light" ? 'white' : 'black'

I would also like to create fake data. I want mock data to be returned when developing in Qt Design Studio when accessing MyCppObject.variable1. How can this be done and what good architectural solutions can be used for this? Thank you all.

Upvotes: 0

Views: 111

Answers (0)

Related Questions