Anonimista
Anonimista

Reputation: 183

PyQt6 Qml example that uses QQmlListProperty

I'm trying to make sense of the PyQt6 Qml integration example that uses QQmlListProperty here

The Python file I'm currently using: main.py

import sys

from PyQt6.QtCore import pyqtProperty, QCoreApplication, QObject, QUrl
from PyQt6.QtQml import qmlRegisterType, QQmlComponent, QQmlEngine, QQmlListProperty


class Person(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._name = ''
        self._shoeSize = 0

    @pyqtProperty('QString')
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

    @pyqtProperty(int)
    def shoeSize(self):
        return self._shoeSize

    @shoeSize.setter
    def shoeSize(self, shoeSize):
        self._shoeSize = shoeSize


class BirthdayParty(QObject):

    def __init__(self, parent=None):
        super().__init__(parent)
        self._guests = []

    @pyqtProperty(QQmlListProperty)
    def guests(self):
        return QQmlListProperty(Person, self, self._guests)


app = QCoreApplication(sys.argv)

qmlRegisterType(Person, 'People', 1, 0, 'Person')
qmlRegisterType(BirthdayParty, 'BirthdayParties', 1, 0, 'BirthdayParty')

engine = QQmlEngine()

person = QQmlComponent(engine)
person.loadUrl(QUrl.fromLocalFile('example.qml'))
person_object = person.create()

party = QQmlComponent(engine)
party.loadUrl(QUrl.fromLocalFile('example1.qml'))
party_object = party.create()


if person_object is not None:
    print("The person's name is %s." % person_object.name)
    print("They wear a size %d shoe." % person_object.shoeSize)
else:
    for error in person_object.errors():
        print(error.toString())

example.qml that contains Person named Bob

import People 1.0

Person {
    name: "Bob Jones"
    shoeSize: 12
}

example1.qml that contains the BirtdayParty

import BirthdayParties 1.0

BirthdayParty {
    guests:[
        Person {
            name: "Bob Jones"
            shoeSize: 12
        },
        Person {
            name: "Bob Jones 1"
            shoeSize: 13
        }
    ]
}

The error I'm getting:

QQmlComponent: Component is not ready
The person's name is Bob Jones.
They wear a size 12 shoe.

According to my research the 'Component not ready' indicates an error in Qml syntax. Also if I change example1.qml to

import BirthdayParties 1.0

BirthdayParty {
    guests:[
    ]
}

the script runs without errors. So I guess I don't know how to make a list of Qml objects in a qml file. This example:

import QtQuick

Item {
    states: [
        State { name: "loading" },
        State { name: "running" },
        State { name: "stopped" }
    ]
}

from here is an example of a list of objects but I can't make my list work.

I am running main.py from the Windows 10 terminal.

Upvotes: 0

Views: 73

Answers (0)

Related Questions