Aaron
Aaron

Reputation: 839

Importing QML from a Resource (QRC) file with PySide2

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.

Upvotes: 3

Views: 1934

Answers (1)

eyllanesc
eyllanesc

Reputation: 243965

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

Upvotes: 4

Related Questions