使用 PySide2 从资源 (QRC) 文件导入 QML [英] Importing QML from a Resource (QRC) file with PySide2

查看:81
本文介绍了使用 PySide2 从资源 (QRC) 文件导入 QML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在resource.qrc"中添加了一个简单的 QML 组件(qml/MyButton").文件:

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

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

然后我将 QRC 编译为 python 模块:

I then compiled the QRC to a python module with:

pyside2-rcc -o resource.py resource.qrc

pyside2-rcc -o resource.py resource.qrc

然后我在main.py中导入resource.py:

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

并在 main.qml 中调用 MyButton 组件:

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 {

    }
}

这是qml/MyButton.qml":

This is "qml/MyButton.qml":

import QtQuick 2.0
import QtQuick.Controls 2.13

Button {
    text: 'Click Me'
}

当我运行程序时,我收到MyButton 不是类型"的错误消息.我想通过使用python生成的资源文件来使用QML组件.我不知道我做错了什么.

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.

推荐答案

如果 .qml 位于主文件旁边,则自动导入,但在您的情况下 MyButton.qml 不在 main.qml 旁边,因此包必须是进口:

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 {
    }
}

这篇关于使用 PySide2 从资源 (QRC) 文件导入 QML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆