Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

10 Tips to Make Your QML Code Faster and More Maintainable

Modernize your code for fun and profit

add_executable(myapp main.cpp)

qt_add_qml_module(myapp
 URI "org.kde.myapp"
 QML_FILES Main.qml
)
qmlRegisterType("org.kde.myapp", 1, 0, "MyThing");
class MyThing : public QObject
{
    Q_OBJECT
    QML_ELEMENT
};
qt_add_qml_module(myapp
 URI "org.kde.myapp"
 QML_FILES Main.qml
 DEPENDENCIES QtCore
)
namespace MyApp {

class MyHelper : public QObject {
    Q_OBJECT
};

class MyThing : public QObject {
    Q_OBJECT
    QML_ELEMENT
    Q_PROPERTY(MyHelper *helper READ helper CONSTANT) // bad
    Q_PROPERTY(MyApp::MyHelper *helper READ helper CONSTANT) // good
    ...
};
}
property var size: 10 // bad
property int size: 10 // good

property var thing // bad
property MyThing thing // good
Item {
    id: thing

    property int size: 10

    Rectangle {
        width: parent.size // bad, Item has no 'size' property
        height: thing.height // good, lookup via id

        color: parent.enabled ? "red" : "black" // good, Item has 'enabled' property
    }
}
function calculateArea(width: double, height: double) : double {
    return width * height
}
MouseArea {
    onClicked: event => console.log("clicked at", event.x, event.y)
}
Item {
    id: root
    property int size: 10

    Rectangle {
        width: size // bad, unqualified lookup
        height: root.size // good, qualified lookup
    }
}
ListView {
    model: MyModel

    delegate: ItemDelegate {
        text: name // bad, lookup from context
        icon.name: model.iconName // more readable, but still bad

        required property bool active // good, using required property
        checked: active
    }
}
pragma ComponentBehavior: Bound

import QtQuick

Item {
    id: root

    property int delegateHeight: 10

    ListView {
        model: MyModel

        delegate: Rectangle {
            height: root.delegateHeight // good with ComponentBehavior: Bound, bad otherwise
        }
    }
}

About KDAB


6 Comments

23 - Oct - 2024

Robert

23 - Oct - 2024

Nicolas Fella

25 - Oct - 2024

Lorenzo

25 - Oct - 2024

Nicolas Fella

28 - Oct - 2024

Lorenzo

11 - Jan - 2025

Peter

NicolasFella

Nicolas Fella

Software Engineer

Learn Modern C++

Learn more