[QT] Menu & Dynamic Menu

👉🏻 QML에서 메뉴를 만드는 방법을 설명합니다.
Explains how to create a menu in QML.

👉🏻 설명은 주석을 참고 하세요
Please refer to the comments for explanation.

✔️Main.cpp

— Main.cpp파일은 수정하지 않아도 됩니다.
You do not need to modify the Main.cpp file.

✔️Main.qml

import QtQuick
import QtQuick.Controls

// QML에서 ApplicationWindow 사용 추천
// Recommended to use ApplicationWindow in QML
ApplicationWindow {
    width: 400
    height: 300
    visible: true
    title: "Menu Example"

    // == 컴포넌트 메뉴 / Component Menu ==
    menuBar: AppMenuBar {}

    // 텍스트 전체 정렬 / Align entire text
    Text {
        text: "Center Text"
        anchors.centerIn: parent
    }

    // 수평만 중앙 정렬 / Center alignment only horizontally
    Text {
        text: "horizontalCenter"
        anchors.horizontalCenter: parent.horizontalCenter
        // anchors.left가 있어야 leftMargin이 적용됨.
        anchors.top: parent.top
        anchors.topMargin: 50

    }

    // 수직 중앙 정렬 / vertical center alignment
    Text {
        text: "Vertical Center"
        anchors.verticalCenter: parent.verticalCenter
        // anchors.left가 있어야 leftMargin이 적용됨.
        anchors.left: parent.left
        anchors.leftMargin: 30
    }
}

✔️ NewWindow.qml

import QtQuick
import QtQuick.Controls

/*-----------------------------------------------------------------------------------------------

    -- 동적 메뉴  / Dynamic Menu--
    이 창 내에서 컴포넌트를 정의하고 버튼 클릭시 메뉴를 교체하는 메뉴
    A menu that defines components within this window and replaces them when a button is clicked.

-------------------------------------------------------------------------------------------------*/

ApplicationWindow {
    id: root
    width: 400
    height: 300
    visible: true
    title: "Dynamic Menu Example"

    property bool adminMode: false

    //  메뉴를 실제로 보여주는 곳 / Where the menu actually appears
    menuBar: Loader {
        id: menuLoader
        sourceComponent: adminMode ? adminMenu : normalMenu
    }

    // 일반 사용자 메뉴 / General user menu
    Component {
        id: normalMenu
        MenuBar {
            Menu {
                title: "File"
                MenuItem {
                    text: "Open"
                    onTriggered: console.log("Open clicked (normal user)")
                }
                MenuItem {
                    text: "Exit"
                    onTriggered: Qt.quit()
                }
            }
            Menu {
                title: "Help"
                MenuItem {
                    text: "About"
                    onTriggered: console.log("About clicked (normal user)")
                }
            }
        }
    }

    //  관리자 메뉴 / Administrator Menu
    Component {
        id: adminMenu
        MenuBar {
            Menu {
                title: "Admin"
                MenuItem {
                    text: "User Management"
                    onTriggered: console.log("User management clicked (admin)")
                }
                MenuItem {
                    text: "System Log"
                    onTriggered: console.log("System log clicked (admin)")
                }
            }
            Menu {
                title: "Tools"
                MenuItem {
                    text: "Diagnostics"
                    onTriggered: console.log("Diagnostics clicked (admin)")
                }
            }
        }
    }

    //  버튼으로 메뉴 교체 / Change menu with buttons
    Button {
        text: adminMode ? "Switch to Normal Menu" : "Switch to Admin Menu"
        anchors.centerIn: parent
        onClicked: adminMode = !adminMode
    }
}

✔️ AppMenuBar.qml

import QtQuick
import QtQuick.Controls

// == 이 AppMenuBar파일이 하나의 컴포넌트가 됨 / This AppMenuBar file becomes a component ==

    MenuBar {
        Menu {
            title: qsTr("File")
            MenuItem {
                text: qsTr("Open")
                onTriggered: console.log("Open clicked")
            }
            MenuItem {
                text: qsTr("Exit")
                onTriggered: Qt.quit()
            }
        }
        Menu {
            title: qsTr("Edit")
            MenuItem {
                text: qsTr("Write")
                onTriggered: console.log("Write clicked")
            }
            MenuItem {
                text: qsTr("Action")
                onTriggered: Qt.quit()
            }
        }

        Menu {
            title: qsTr("View")
            MenuItem {
                text: qsTr("Show left sidebar")
                onTriggered: console.log("About clicked")
            }
            MenuItem {
                text: qsTr("Show right sidebar")
                onTriggered: console.log("About clicked")
            }
        }
        Menu {
            title: qsTr("Window")
            MenuItem {
                text: qsTr("Open New Window")
                onTriggered: {
                    console.log("Open New Window clicked")

                    // 새 창 컴포넌트 생성, 메뉴선택시 새창 오픈
                    // Create a new window component, open a new window when a menu is selected
                    const comp = Qt.createComponent("NewWindow.qml")
                    if (comp.status === Component.Ready) {
                        const win = comp.createObject(null)
                        if (win) win.show()
                    } else {
                        console.error("Component load error:", comp.errorString())
                    }
                }
            }
            MenuItem {
                text: qsTr("Show right sidebar")
                onTriggered: console.log("About clicked")
            }
        }
        // 맥os에서는 help나 이름이 이상하면 메뉴가 안 나타날 수 있음
        // In macOS, the menu may not appear if the help or name is strange.
        Menu {
            title: qsTr("help center")
            MenuItem {
                text: qsTr("Record list")
                onTriggered: console.log("About clicked")
            }
            MenuItem {
                text: qsTr("Record help")
                onTriggered: console.log("About clicked")
            }
        }
    }

✔️ CMakeList.txt

— qml파일이 아래의 코드처럼 등록되어 있어야 합니다.
The qml file must be registered as shown in the code below.

qt_add_qml_module(appMenu
    URI Menu
    VERSION 1.0
    QML_FILES
        Main.qml
        AppMenuBar.qml
        NewWindow.qml
)

✔️ 스크린샷 / ScreenShot

Leave a Reply