Importing QML from a Resource (QRC) file with PySide2

我怕爱的太早我们不能终老 提交于 2020-12-13 03:12:17

问题


I have added a simple QML component ("qml/MyButton") to my "resource.qrc" file:

<RCC>
<qresource prefix="/">
    <file>qml/MyButton.qml</file>
</qresource>
</RCC>

I then compiled the QRC to a python module with:

pyside2-rcc -o resource.py resource.qrc

Then I imported resource.py in main.py:

import sys
import os

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

import resource

if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))

    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

And called MyButton component in main.qml:

import QtQuick 2.13
import QtQuick.Window 2.13

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    MyButton {

    }
}

This is "qml/MyButton.qml":

import QtQuick 2.0
import QtQuick.Controls 2.13

Button {
    text: 'Click Me'
}

When I run the program I get the error that "MyButton is not a type". I want to use the QML component by using the python generated resource file. I don't know what I am doing wrong.


回答1:


Automatic import if the .qml is next to the main file but in your case MyButton.qml is not next to the main.qml so the package has to be imported:

import QtQuick 2.13
import QtQuick.Window 2.13

import "qrc:/qml"

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    MyButton {
    }
}


来源:https://stackoverflow.com/questions/64978277/importing-qml-from-a-resource-qrc-file-with-pyside2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!