[QT QML]시그널과 슬롯 – 컴포넌트 / Signal and Slot – Component

👉🏻 아래의 코드는 버튼 클릭시 카운터를 증가시키고 감소시키는 앱입니다.
The code below is an app that increases and decreases the counter when the button is clicked.

👉🏻 아래의 코드는 각 2개의 컴포넌트(qml파일) 사이의 시그널과 슬롯을 통해서 이벤트를 처리합니다.
The code below handles the event through the signals and slots between each of the two components (qml file).

👉🏻 혹시 맥os를 사용할 경우 다크모드로 설정하면 Button{} 부분은 안보일 수 있습니다.
If you use macos, set it in dark mode, button{} part may not be visible.

👉🏻 왜냐하면 기본 버튼 사용시 맥OS의 다크모드 설정을 반영하기 때문에 커스텀 설정이 적용되지 않습니다.
Because when using the default button, the custom setting does not apply because it reflects the macOS’ dark mode setting.

👉🏻 그래서 커스텀 버튼을 만들었습니다.( CusomButton.qml)
So I created a custom button (CusomButton.qml)

👉🏻 나머지 설명은 이전 포스트를 참조하세요
Please refer to the previous post for the rest of the explanation

👉🏻 코드 / Code

✔️Main.qml

import QtQuick
import QtQuick.Controls


ApplicationWindow {
    width: 640
    height: 480
    visible: true
    title: "Component Event Example"

    Rectangle {
        id: root
        anchors.fill: parent
        color: "white"

        property int count: 0

        Column {
            anchors.fill: parent
            spacing: 20

            // 카운터 출력 / Counter Output
            Text {
                anchors.horizontalCenter: parent.horizontalCenter

                font.pixelSize: 24
                text: "Count: " + root.count
            }

            // 자식 컴포넌트 사용 / Using Child Components
            CounterControls {
                id: controls
                anchors.horizontalCenter: parent.horizontalCenter

                // 자식 시그널을 부모가 처리(슬롯)
                // Parent Processes Child Signal (Slot)
                onIncrementRequested: {
                    root.count++
                    console.log("Increment:", root.count)
                }
                onDecrementRequested: {
                    if (root.count > 0) root.count--
                    console.log("Decrement:", root.count)
                }
            }
        }
    }
}

✔️CounterControls.qml

import QtQuick
import QtQuick.Controls

Item {
    id: control

    // Item 전체의 기본 크기를 Row 크기에 맞추기
    // Set the default size of the entire item to the Row size

    implicitWidth: row2.implicitWidth
    implicitHeight: row2.implicitHeight

    // Signal
    signal incrementRequested()
    signal decrementRequested()



    Column{

        Text {
            text: "Counter Controls"
            anchors.horizontalCenter: parent.horizontalCenter
        }

        Row {
            id: row
            spacing: 10
            width:row2.implicitWidth

            // Row의 크기를 부모 Item에 전달
            // anchors.fill: parent

            /*
                맥OS가 다크모드일 경우에는 아래 디폴트 버튼이 안보일 수 있음.
                If the macOS is in dark mode, the following default buttons may not be visible.
            */

            // default Button
            Button {
                text: "Increase"
                font.pixelSize: 16
                palette.text: "black"
                onClicked: control.incrementRequested()
            }


            Button {
                id:btn2
                text: "Decrease"
                font.pixelSize: 16
                palette.text: "black"
                onClicked: control.decrementRequested()
            }

        }

        // Custom Button
        Row{
            id:row2
            CustomButton {
                text: "Increase"
                backgroundColor: "#4CAF50" // green

                onClicked: {
                    //root.count++
                    control.incrementRequested()
                }
            }

            CustomButton {
                text: "Decrease"
                backgroundColor: "#FFA500" // orange

                onClicked: {
                    //if (root.count > 0) root.count--
                    control.decrementRequested()
                }
            }

        }
    }
}

✔️CustomButton.qml

import QtQuick
import QtQuick.Controls


Rectangle {
    id: customBtn
    property alias text: label.text
    property color backgroundColor: "#5C6BC0"
    property color textColor: "black" // color --> 문자열 색상 지정하는 타입 / Type to color string
    property real radiuss: 8 // real --> 실수형 숫자를 지정하는 타입 / Type to specify a real number
    property real fontSize: 16

    width: 120
    height: 40
    color: backgroundColor    // 반드시 필요 / absolutely necessary
    radius: radiuss // radius이름이 동일 하면 충돌일어남 / If radius names are the same, it will result in a collision

    signal clicked // 외부에서 onClicked슬롯으로 실행됨. / Executed externally as an on-Clicked slot.

    Text {
        id: label
        anchors.centerIn: parent
        color: textColor
        font.pixelSize: fontSize
        text: "custom button"
    }

    MouseArea {
        anchors.fill: parent
        hoverEnabled: true

        onClicked: customBtn.clicked( // 컴포넌트 기본 슬롯 / Component Default Slot
            //console.log(`btn print`)
        )

        onPressed: customBtn.color = Qt.darker(customBtn.backgroundColor, 1.2)
        onReleased: customBtn.color = customBtn.backgroundColor

        onEntered: customBtn.color = Qt.lighter(customBtn.backgroundColor, 1.1)
        onExited: customBtn.color = customBtn.backgroundColor
    }
}

👉🏻 스크린 샷 / ScreenShot

Leave a Reply