PySide2를 사용하여 리소스 (QRC) 파일에서 QML 가져 오기

Nov 24 2020

"resource.qrc"파일에 간단한 QML 구성 요소 ( "qml / MyButton")를 추가했습니다.

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

그런 다음 QRC를 다음을 사용하여 파이썬 모듈로 컴파일했습니다.

pyside2-rcc -o resource.py resource.qrc

그런 다음 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_())

main.qml에서 MyButton 구성 요소를 호출했습니다.

import QtQuick 2.13
import QtQuick.Window 2.13

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

    MyButton {

    }
}

이것은 "qml / MyButton.qml"입니다.

import QtQuick 2.0
import QtQuick.Controls 2.13

Button {
    text: 'Click Me'
}

프로그램을 실행할 때 "MyButton이 유형이 아닙니다"라는 오류가 발생합니다. 파이썬에서 생성 한 리소스 파일을 사용하여 QML 구성 요소를 사용하고 싶습니다. 내가 뭘 잘못하고 있는지 모르겠다.

답변

1 eyllanesc Nov 24 2020 at 06:54

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