Search code examples
pythonqmlpyside2

Cannot use ApplicationWindow (QML) on PySide2


I'm trying to run a simple Qt application using QML and more specifically ApplicationWindow.

My Python code is a simple QML caller:

import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtQuick import QQuickView
from PySide2.QtCore import QUrl

if __name__ == '__main__':

    app = QApplication(sys.argv)

    view = QQuickView()
    url = QUrl('view.qml')
    view.setSource(url)
    view.show()

    sys.exit(app.exec_())

and my QML file is a simple ApplicationWindow with Title, width and height:

import QtQuick 2.0

ApplicationWindow {

    title: "Qt Quick Controls Gallery"

    width: 640
    height: 480
}

Running the code results in a blank screen, with default title ("gui.py", instead of the title given on QML), and with default width and height (not the specified on the QML file):

enter image description here

I can run other components, like rectangles, buttons and canvas without problems. My problem is specifically with the ApplicationWindow component, that I would like to use since it's the standard for QML apps.

I'm trying to stick with PySide2 as it's becoming the supported for Python Qt, but I'm accepting PyQt solutions as well, of course.


Solution

  • First, as pyside returns:

    QQuickView does not support using windows as a root item. If you wish to create your root window from QML, consider using QQmlApplicationEngine instead.

    This is a working example:

    main.py

    import sys
    from PySide2.QtWidgets import QApplication
    from PySide2.QtCore import Qt, QCoreApplication
    from PySide2.QtQml import QQmlApplicationEngine
    
    if __name__ == '__main__':
    
        app = QApplication(sys.argv)
    
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    
        engine = QQmlApplicationEngine('view.qml')
    
        sys.exit(app.exec_())
    

    view.qml

    import QtQuick.Controls 2.4
    import QtQuick 2.0
    
    ApplicationWindow {
    
        title: "Qt Quick Controls Gallery"
        visible: true
        width: 640
        height: 480
        Rectangle {
            width: 30
            height: 30
            color: "blue"
        }
    }