사용 사례 - QML에 자바스크립트 통합
JavaScript 코드를 QML에 쉽게 통합하여 UI 로직, 명령형 제어 또는 기타 이점을 제공할 수 있습니다.
속성 값에 자바스크립트 표현식 사용
자바스크립트 표현식은 QML에서 바인딩으로 사용할 수 있습니다. 예를 들어
Item { width: Math.random() height: width < 100 ? 100 : (width + 50) / 2 }
Math.random()과 같은 함수 호출은 인수가 변경되지 않는 한 재평가되지 않는다는 점에 유의하세요. 따라서 Math.random() 바인딩은 하나의 난수가 되어 재평가되지 않지만 너비가 다른 방식으로 변경되면 이를 고려하기 위해 높이 바인딩이 재평가됩니다.
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 파일처럼 함수를 사용해야 하는 .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 표현식에 대한 전체 문서를 참조하세요.
© 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.