Search code examples
pythonqmlqtquick2shortcutpyside2

The Shortcut in a PySide2 MenuItem prevents window from showing


I'm trying to create a very simple ApplicationWindow using PySide2 (Qt for Windows) and QML.

main.py

import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import QUrl
from PySide2.QtQml import QQmlApplicationEngine

if __name__ == "__main__":
    app = QApplication(sys.argv)
    url = QUrl("mainWindow.qml")
    engine = QQmlApplicationEngine()
    engine.load(url)
    sys.exit(app.exec_())

qml file

import QtQuick.Controls 2.4

ApplicationWindow {
    id: mainWindow
    visible: true
    title: "MainWindow"
    width: 640
    height: 480

    menuBar: MenuBar {
        id: menuBar

        Menu {
            id: editMenu
            title: "&Edit"

            MenuItem {
                id: copyItem
                text: "Copy"
                // This doesn't work:
                // shortcut: "Ctrl+C"
                // This doesn't work either:
                // shortcut: StandardKey.Copy
            }
        }
    }
}

As shown, the code runs and displays an ApplicationWindow with a MenuBar and the Menu. But if I outcomment either of the two shortcut variants the window isn't shown at all. I don't understand, why. My example follows the Qt documentation on MenuItems.


Solution

  • In QML there are 2 types of items: Qt Quick Controls 1 and Qt Quick Controls 2. Both groups have items with the same name but they differ in their properties, in your case MenuItem of Qt Quick Controls 2 does not have a shortcut property but instead Qt Quick Controls 1 if it has it so the solution is to change the import:

    import QtQuick 2.11         // <---
    import QtQuick.Controls 1.4 // <---
    
    ApplicationWindow {
        id: mainWindow
        visible: true
        title: "MainWindow"
        width: 640
        height: 480
    
        menuBar: MenuBar {
            id: menuBar
            Menu {
                id: editMenu
                title: "&Edit"
    
                MenuItem {
                    id: copyItem
                    text: "Copy"
                    shortcut: StandardKey.Copy
                    onTriggered: console.log("copy")
                }
            }
        }
    }