QQuickView仅支持加载源自QQuickItem错误的根对象?

时间:2014-09-19 10:12:46

标签: python pyqt qml pyqt5

我使用pyqt5编写简单的hello世界。但是当我启动它时,我得到错误:

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.

我试图解决它,但我想我不明白发生了什么。有人可以在更多细节中向我解释这个错误,我该如何解决?

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()

                       }



          }



}

1 个答案:

答案 0 :(得分:9)

错误信息非常明确:ApplicationWindow不是QQuickItem,因此您无法使用QQuickView加载它。

之所以如此,是因为它们都继承了QQuickWindow,因此ApplicationWindow与QQuickView存在冲突。要加载ApplicationWindow,您需要使用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()