Are native menu bars for MacOS supported in Qt Quick?

Viewed 690

in a project I'm working on I've got to the point where I need a menu bar (File, Edit, View etc.) to interact with. I work on a Mac and so I want to be able to use the menu bar already provided in OS X, but from all the documentation I've seen and questions that have been answered it looks like that is only supported properly in QMainWindow, a part of Qt Widgets and not Qt Quick. Are native menu bars supported for Mac in Qt Quick, or will I have to write some platform-specific code to implement one? Thanks in advance for any help!

2 Answers

Like Rolf Winter said, you can have a native Mac OS Menu Bar with Qt Quick / QML, without using Widgets. It comes from MenuBar QML Type.

Sure, it is a Qt Labs component, so there is certain risk of using it in production (no guarantee/stability).

Here's a simplified example:

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import Qt.labs.platform 1.1

ApplicationWindow {
    width: 500
    minimumWidth: 500
    height: 300
    minimumHeight: 300
    visible: true
    title: qsTr("Testing Mac OS native Menu Bar in Qt Quick")

    MenuBar {
        id: menuBar

        Menu {
            id: fileMenu
            title: qsTr("File")

            MenuItem {
                text: qsTr("Ololo")
                onTriggered: console.debug("ololo menu item clicked")
            }

            // this one won't show up in File menu because of its `role`,
            // and it will actually appear in the main menu - under the application name,
            // where you'd usually expect About menu to be
            MenuItem {
                //text: qsTr("About")    // no need to set the text,
                role: MenuItem.AboutRole // because it gets generated
                onTriggered: console.debug("show your About window")
            }
        }

        Menu {
            id: editMenu
            title: qsTr("Edit")

            MenuItem {
                text: qsTr("Stuff")
                onTriggered: console.debug("stuff menu item clicked")
            }
        }
    }
}

Your question is about Mac OS, so I didn't do anything to make the menu cross-platform (for instance, on Windows you might want to move About menu item to Help menu and actually give it some text).

Anyway, on Mac OS the result will be the following:

Mac OS Menu Bar created with Qt Quick

As you can see, Edit menu also gets populated with a couple of "bonus" items (not sure if that is handled by Qt or Mac OS).

Just in case, my environment:

  • Mac OS 11.5.2
  • Qt 5.15.2

You could even try getting it from cpp by adding a QMenuBar and then attach the menus you want, like File, Edit etc. Take a look at this https://doc.qt.io/qt-5/qmenubar.html I did this because i wasn't using the ApplicationWindow from QML but a custom one which is derived from QQuickWindow.

Related