이 페이지에서

QML 코딩 규칙

이 문서에는 당사의 문서와 예제에서 따르고 있으며, 다른 분들도 따르기를 권장하는 QML 코딩 규칙이 포함되어 있습니다.

QML 객체 선언

본 문서의 모든 설명 및 예제에서 QML 객체 속성은 항상 다음 순서로 구성됩니다:

  • id
  • 속성 선언
  • 신호 선언
  • JavaScript 함수
  • 객체 속성
  • 자식 객체

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

예를 들어, 가상의 사진 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
    }
}

필수 속성

컴포넌트 외부에서 정의된 데이터가 필요한 경우, '필수 속성(Required Properties)'을 사용하여 이를 명시하십시오. 필수 속성은 반드시 설정되어야 하며, 그렇지 않으면 컴포넌트 생성이 실패합니다. 필수 속성은 성능이 더 우수하고, 사용자와 툴 모두 외부 속성의 유형을 파악할 수 있게 해주기 때문에, 명시되지 않은 조회보다 선호됩니다. 또한, 이를 통해 컴포넌트가 생성되는 환경에 대해 컴포넌트가 해야만 했던 가정들을 없앨 수 있습니다.

신호 핸들러

신호 핸들러에서 매개변수를 처리할 때는 매개변수 이름을 명시적으로 지정하는 함수를 사용하십시오:

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

JavaScript 코드

가독성과 유지 관리성을 높이기 위해, 간단한 표현식인 경우에도 일반적으로 각 속성을 별도의 줄에 선언합니다.

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);
    }
}

© 2026 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.