QML 코딩 규칙

이 문서에는 문서와 예제에서 따르고 다른 사람들이 따를 것을 권장하는 QML 코딩 규칙이 포함되어 있습니다.

QML 객체 선언

문서와 예제 전체에서 QML 객체 속성은 항상 다음 순서로 구조화됩니다:

  • id
  • 속성 선언
  • 시그널 선언
  • 자바스크립트 함수
  • 객체 속성
  • 자식 객체

가독성을 높이기 위해 이러한 서로 다른 부분을 빈 줄로 구분합니다.

예를 들어 가상의 사진 QML 객체는 다음과 같습니다:

Rectangle {
    id: photo                                               // id on the first line makes it easy to find an object

    property bool thumbnail: false                          // property declarations
    property alias image: photoImage.source

    signal clicked                                          // signal declarations

    function doSomething(x)                                 // javascript functions
    {
        return x + photoImage.width;
    }

    color: "gray"                                           // object properties
    x: 20                                                   // try to group related properties together
    y: 20
    height: 150
    width: {                                                // large bindings
        if (photoImage.width > 200) {
            photoImage.width;
        } else {
            200;
        }
    }

    states: [
        State {
            name: "selected"
            PropertyChanges { target: border; color: "red" }
        }
    ]

    transitions: [
        Transition {
            from: ""
            to: "selected"
            ColorAnimation { target: border; duration: 200 }
        }
    ]

    Rectangle {                                             // child objects
        id: border
        anchors.centerIn: parent
        color: "white"

        Image {
            id: photoImage
            anchors.centerIn: parent
        }
    }
}

그룹화된 속성

속성 그룹에서 여러 속성을 사용하는 경우 가독성을 높이려면 점 표기법 대신 그룹 표기법을 사용하는 것이 좋습니다.

예를 들어, 이

Rectangle {
    anchors.left: parent.left; anchors.top: parent.top; anchors.right: parent.right; anchors.leftMargin: 20
}

Text {
    text: "hello"
    font.bold: true; font.italic: true; font.pixelSize: 20; font.capitalization: Font.AllUppercase
}

는 다음과 같이 작성할 수 있습니다:

Rectangle {
    anchors { left: parent.left; top: parent.top; right: parent.right; leftMargin: 20 }
}

Text {
    text: "hello"
    font { bold: true; italic: true; pixelSize: 20; capitalization: Font.AllUppercase }
}

자격이 없는 액세스

가독성과 성능을 개선하려면 항상 부모 컴포넌트의 프로퍼티를 명시적으로 ID로 참조하세요:

Item {
    id: root

    property int rectangleWidth: 50

    Rectangle {
        width: root.rectangleWidth
    }
}

필수 속성

컴포넌트 외부에 정의된 데이터가 필요한 경우 필수 속성을 사용하여 이를 명시적으로 지정하세요. 필수 속성을 설정하지 않으면 컴포넌트 생성이 실패합니다. 필수 속성은 더 성능이 뛰어나고 사용자와 도구 모두 외부 속성의 유형을 추론할 수 있기 때문에 한정되지 않은 조회보다 선호됩니다. 또한 컴포넌트가 생성되는 환경에 대한 가정을 제거할 수 있습니다.

시그널 핸들러

시그널 핸들러에서 매개변수를 처리할 때는 명시적으로 이름을 지정하는 함수를 사용합니다:

MouseArea {
    onClicked: event => { console.log(`${event.x},${event.y}`); }
}

자바스크립트 코드

스크립트가 단일 표현식인 경우 인라인으로 작성하는 것이 좋습니다:

Rectangle { color: "blue"; width: parent.width / 3 }

스크립트 길이가 몇 줄에 불과한 경우에는 일반적으로 블록을 사용합니다:

Rectangle {
    color: "blue"
    width: {
        var w = parent.width / 3;
        console.debug(w);
        return w;
    }
}

스크립트의 길이가 두 줄 이상이거나 다른 객체에서 사용할 수 있는 경우 함수를 만들어 다음과 같이 호출하는 것이 좋습니다:

function calculateWidth(object : Item) : double
{
    var w = object.width / 3;
    // ...
    // more javascript code
    // ...
    console.debug(w);
    return w;
}

Rectangle { color: "blue"; width: calculateWidth(parent) }

또한 함수 서명에서 매개변수와 반환 유형을 모두 즉시 볼 수 있으므로 애플리케이션을 더 쉽게 추론하고 리팩터링하기 위해 함수에 유형 주석을 추가하는 것이 좋습니다.

긴 스크립트의 경우 함수를 자체 JavaScript 파일에 넣고 다음과 같이 가져옵니다:

import "myscript.js" as Script

Rectangle { color: "blue"; width: Script.calculateWidth(parent) }

코드가 한 줄보다 길어서 블록 내에 있는 경우 세미콜론을 사용하여 각 문장의 끝을 표시합니다:

MouseArea {
    anchors.fill: parent
    onClicked: event => {
        var scenePos = mapToItem(null, event.x, event.y);
        console.log("MouseArea was clicked at scene pos " + scenePos);
    }
}

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.