Structure and Scale

QML has grown to be a fairly unstructured language. It may be due to its heritage as a rapid prototyping language or possibly its javascript lineage.

Because of this, many C++ developers find it difficult to organize QML for scalability.

Here is a coding standard that has evolved over many years of QML experience. It provides a well structured approach to creating identifiers for objects as well as a clean hierarchical approach to defining properties.

Let's have a look:

import QtQuick 2.5

Item {
    id: root

    signal clicked
    property alias text: _textButton.text

    function open() { }
    function close() { }

    Rectangle {
        id: _rectangleButton
        anchors.centerIn: parent
        width: 100
        height: 40

        Text {
            id: _textButton
            anchors.fill: parent
            anchors.margins: 4

            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
            elideMode: Text.ElideRight
        }

        MouseArea {
            id: _mouseAreaButton
            anchors.fill: parent
            onClicked: { 
                root.clicked();
            }
        }
    }
}

The General Rules

Here are a collection of general rules to follow to ensure every developer has equal opportunity for QML code structure and scalability. These techniques work very well in projects ranging from a few lines of code to 100,000+ lines of code.

The top-most element of every page must have root as its identifier.

Using root as the identifier creates a known standard for every QML component separated into its own QML file. This speeds up development as the developer knows the root element of a document is identified as root.

All identifiers (with the exception of the root element as well as QtObject elements) must follow this indistinguishable format, _[componentName][componentDescription]

Using _[componentName][componentDescription] allows for a clean standardization of element identifiers. It allows a developer to know what type of component they are referencing to. When paired with developer knowledge of the codebase; specifically QML element types, this single guideline can save hours of developer time.

...
Item {
    id: _itemContainer
    // ...
}
...
...
Button {
    id: _buttonOpenList
    // ...
}
...
...
ListView {
    id: _listViewAlbums
    // ...
}
...

Hierarchical Order of Declarations

A common hierarchy promotes code sustainability and clarity. This guideline is similar to a Q_PROPERY/public/private/protected/signals/slots hierarchy in C++.

// Qt imports first, then custom imports
import QtQuick 2.5
// Alias Qt imports that are rarely used (that a developer wouldn't understand)
import QtGraphicalEffects 1.0 as QGE

import custom.import 1.0