QML에서 시그널은 컴포넌트 간 통신을 위한 메커니즘으로, 특정 이벤트 발생 시 다른 객체에 알리는 역할을 합니다. 파라미터를 포함할 수 있으며, on 구문이나 Connections 요소를 통해 처리합니다.
1. 시그널 정의 방식
사용자 정의 컴포넌트에서 signal 키워드로 시그널을 선언할 수 있습니다.
// MyComponent.qml
import QtQuick 2.15
Item {
id: componentRoot
// 파라미터 없는 시그널
signal buttonPressed()
// 문자열 및 정수 파라미터 시그널
signal dataReceived(string text, int value)
// 명명된 파라미터 시그널(가독성 향상)
signal updateStatus(var payload, int index)
}
2. 시그널 트리거 방법
직접 시그널 호출로 이벤트를 발생시킵니다.
// MyComponent.qml
Item {
signal eventTriggered(string name)
MouseArea {
anchors.fill: parent
onClicked: {
componentRoot.eventTriggered("MainButton")
}
}
}
3. 시그널 연결 방식
3.1 현재 컴포넌트 내부 처리
// MyComponent.qml
Item {
id: root
signal dataAvailable(string content)
onDataAvailable: (content) => {
console.log("데이터 준비 완료:", content)
}
Timer {
running: true
interval: 1000
onTriggered: root.dataAvailable("로딩 완료")
}
}
3.2 외부 컴포넌트 연결
// ParentComponent.qml
Item {
MyComponent {
id: childComponent
}
Connections {
target: childComponent
function onDataAvailable(content) {
console.log("상위 컴포넌트 수신:", content)
}
}
}
4. 시그널과 함수 연결
시그널을 함수에 바인딩할 수 있습니다.
Item {
signal timeUpdated(int current)
function displayTime(time) {
console.log("현재 시간:", time)
}
Component.onCompleted: {
timeUpdated.connect(displayTime)
timeUpdated(1000)
}
}
5. 연결 해제 방법
Item {
id: root
signal eventOccurred()
function handleEvent() { console.log("이벤트 처리") }
Component.onCompleted: {
eventOccurred.connect(handleEvent)
eventOccurred()
eventOccurred.disconnect(handleEvent)
eventOccurred()
}
}
6. 실제 사용 사례
6.1 커스텀 버튼 컴포넌트
// CustomButton.qml
import QtQuick 2.15
Rectangle {
id: buttonRoot
signal pressEvent(string btnId)
width: 120; height: 60
color: "lightgreen"
Text { text: "클릭"; anchors.centerIn: parent }
MouseArea {
anchors.fill: parent
onClicked: buttonRoot.pressEvent("CustomBtn")
}
}
6.2 부모 컴포넌트에서 자식 시그널 감지
// MainWindow.qml
Window {
width: 400; height: 300
CustomButton {
id: btnInstance
anchors.centerIn: parent
// 방식 1: 직접 on<Signal> 처리
onPressEvent: (id) => {
console.log("버튼 클릭:", id)
}
}
// 방식 2: Connections 처리
Connections {
target: btnInstance
function onPressEvent(id) {
console.log("Connections로 감지:", id)
}
}
}