简体   繁体   English

使用 PySide2 从资源 (QRC) 文件导入 QML

[英]Importing QML from a Resource (QRC) file with PySide2

I have added a simple QML component ("qml/MyButton") to my "resource.qrc" file:我在“resource.qrc”文件中添加了一个简单的 QML 组件(“qml/MyButton”):

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

I then compiled the QRC to a python module with:然后我将 QRC 编译为 python 模块:

pyside2-rcc -o resource.py resource.qrc pyside2-rcc -o resource.py 资源.qrc

Then I imported resource.py in main.py:然后我在main.py中导入resource.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:并在 main.qml 中调用 MyButton 组件:

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":这是“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".当我运行程序时,我收到“MyButton 不是类型”的错误消息。 I want to use the QML component by using the python generated resource file.我想通过使用python生成的资源文件来使用QML组件。 I don't know what I am doing wrong.我不知道我做错了什么。

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:如果 .qml 在主文件旁边,但在您的情况下 MyButton.qml 不在 main.qml 旁边,则自动导入,因此必须导入包:

import QtQuick 2.13
import QtQuick.Window 2.13

import "qrc:/qml"

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

    MyButton {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM