이 페이지에서

QML에 JavaScript 통합

자바스크립트 코드를 QML에 쉽게 통합하여 UI 로직, 명령형 제어 또는 기타 이점을 제공할 수 있습니다.

속성 값으로 JavaScript 표현식 사용하기

QML에서는 JavaScript 표현식을 바인딩으로 사용할 수 있습니다. 예를 들어:

Item {
    width: Math.random()
    height: width < 100 ? 100 : (width + 50) /  2
}

Math.random()과 같은 함수 호출은 인수가 변경되지 않는 한 재평가되지 않는다는 점에 유의하십시오. 따라서 Math.random()에 바인딩된 값은 하나의 난수이며 재평가되지 않지만, width가 다른 방식으로 변경되면 height 바인딩은 이를 반영하여 재평가됩니다.

QML에 JavaScript 함수 추가하기

아래 예제와 같이 QML 항목에 JavaScript 함수를 선언할 수 있습니다. 이를 통해 항목 ID를 사용하여 메서드를 호출할 수 있습니다.

import QtQuick

Item {
    id: container
    width: 320
    height: 480

    function randomNumber() {
        return Math.random() * 360;
    }

    function getNumber() {
        return container.randomNumber();
    }

    TapHandler {
        // This line uses the JS function from the item
        onTapped: rectangle.rotation = container.getNumber();
    }

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

JavaScript 파일 사용

자바스크립트 파일을 사용하면 QML 파일에서 로직을 추상화할 수 있습니다. 이를 위해 먼저, 아래 예시와 같이 함수를 .js 파일 내에 작성합니다.

// myscript.js
function getRandom(previousValue) {
    return Math.floor(previousValue + Math.random() * 90) % 360;
}

그런 다음, 아래 예시와 같이 해당 함수를 사용해야 하는 .qml 파일에 파일을 임포트합니다.

import QtQuick
import "myscript.js" as Logic

Item {
    width: 320
    height: 480

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    TapHandler {
        // This line uses the JS function from the separate JS file
        onTapped: rectangle.rotation = Logic.getRandom(rectangle.rotation);
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

자바스크립트로 계산된 각도만큼 회전된 녹색 사각형

QML에서 사용하는 JavaScript 엔진에 대한 자세한 내용과 브라우저 JS와의 차이점에 대해서는 QML 문서의 JavaScript 표현식 관련 전체 문서를 참조하십시오.

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