aboutsummaryrefslogtreecommitdiffstats
path: root/examples/qml/tutorials/extending-qml-advanced/properties/doc/properties.rst
blob: 9337ad2ab9a0bc90f2fe52f21aa8630d9781efc7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
.. _qml-object-and-list-property-types-example:

Extending QML - Object and List Property Types Example
======================================================

Exporting C++ Properties.

This example builds on :ref:`qml-adding-types-example`.

The Object and List Property Types example shows how to add object and list
properties in QML. This example adds a BirthdayParty type that specifies a
birthday party, consisting of a celebrant and a list of guests. People are
specified using the People QML type built in the previous example.

import examples.properties.people

.. code-block:: javascript

    BirthdayParty {
        host: Person {
            name: "Bob Jones"
            shoe_size: 12
        }
        guests: [
            Person { name: "Leo Hodges" },
            Person { name: "Jack Smith" },
            Person { name: "Anne Brown" }
        ]
    }

Declare the BirthdayParty
-------------------------

The BirthdayParty class is declared like this:

.. code-block:: python

    from person import Person


    # To be used on the @QmlElement decorator
    # (QML_IMPORT_MINOR_VERSION is optional)
    QML_IMPORT_NAME = "People"
    QML_IMPORT_MAJOR_VERSION = 1


    @QmlElement
    class BirthdayParty(QObject):

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

        @Property(Person)
        def host(self):
            return self._host

        @host.setter
        def host(self, h):
            self._host = h

        def guest(self, n):
            return self._guests[n]

        def guestCount(self):
            return len(self._guests)

        def appendGuest(self, guest):
            self._guests.append(guest)

        guests = ListProperty(Person, appendGuest)

The class contains a member to store the celebrant object, and also a
list member storing the Person instances.

In QML, the type of a list properties - and the guests property is a list of
people - are all of type ListProperty. ListProperty is simple value
type that contains a set of functions. QML calls these functions
whenever it needs to read from, write to or otherwise interact with
the list. In addition to concrete lists like the people list used in this
example, the use of QQmlListProperty allows for "virtual lists" and other advanced
scenarios.

Running the Example
-------------------

The main.py file in the example includes a simple shell application that
loads and runs the QML snippet shown at the beginning of this page.