Search code examples
pythonpyqtqmlpyqt5

QQuickView only supports loading of root objects that derive from QQuickItem error?


I wrote simple hello world using pyqt5.But when I start it I get error :

QQuickView only supports loading of root objects that derive from QQuickItem. 

If your example is using QML 2, (such as qmlscene) and the .qml file you 
loaded has 'import QtQuick 1.0' or 'import Qt 4.7', this error will occur. 

To load files with 'import QtQuick 1.0' or 'import Qt 4.7', use the 
QDeclarativeView class in the Qt Quick 1 module.

I tried to solve it but I guess I don't understand what happend.Can somebody explain me this error in more details and how can I solve it ?

Main.py:

#!/usr/bin/python3.4


from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qt import *
from PyQt5.QtQuick import * 

if __name__=='__main__':
    import os
    import sys


class Main(QObject):
    def __init__(self,parent=None):
        super().__init__(parent)
        self.view=QQuickView()
        self.view.setSource(QUrl.fromLocalFile('main.qml'))
    def show(self):
        self.view.show()



app=QApplication(sys.argv)
main=Main()
main.show()
sys.exit(app.exec_())

Main.qml

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.0



ApplicationWindow
{
    signal btnPlayClicked()
    signal btnStopClicked()



    id:app
    width:Screen.desktopAvailableWidth
    height:Screen.desktopAvailableHeight
    color:"black"


    ToolBar{
            y:app.height-height
            height:btnPlay.height
                Button
                        {
                               id:btnPlay
                               x:app.width/2-btnPlay.width
                               text:"Play"
                               onClicked: parent.parent.btnPlayClicked()

                        }
                Button
                       {
                               id:btnStop
                               x:app.width/2
                               text:"Stop"
                               onClicked: parent.parent.btnStopClicked()

                       }



          }



}

Solution

  • The error message is quite clear: ApplicationWindow is a not a QQuickItem, and so you can't use QQuickView to load it.

    The reason why, is that ApplicationWindow and QQuickView are in conflict, because they both inherit QQuickWindow. In order to load an ApplicationWindow, you will need to use a QQmlApplicationEngine:

    class Main(QObject):
        def __init__(self,parent=None):
            super().__init__(parent)
            self.engine = QQmlApplicationEngine(self)
            self.engine.load(QUrl.fromLocalFile('main.qml'))
            self.window = self.engine.rootObjects()[0]
    
        def show(self):
            self.window.show()