扩展QML - 添加类型示例#

添加类型示例展示了如何在QML中添加一个新的对象类型,Person。可以使用Person类型,如下所示

import examples.adding.people

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

声明Person类#

所有QML类型都映射到C++类型。在这里,我们声明了一个基本的C++Person类,其中包含我们希望可以在QML类型中访问的两个属性 - 名称和鞋码。虽然在这个例子中我们使用与QML类型相同的名字为C++类命名,但C++类可以有不同的名字,或出现在一个命名空间中。

Person类的实现相当简单。属性访问器仅仅是返回对象实例的成员。

from PySide6.QtCore import QObject, Property
from PySide6.QtQml import QmlElement

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


@QmlElement
class Person(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._name = ''
        self._shoe_size = 0

    @Property(str)
    def name(self):
        return self._name

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

    @Property(int)
    def shoe_size(self):
        return self._shoe_size

    @shoe_size.setter
    def shoe_size(self, s):
        self._shoe_size = s

运行示例#

示例中的main.py文件包括一个简单的shell应用程序,该应用程序加载并运行本页开头所示的QML片段。

下载 示例

# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

"""PySide6 port of the qml/examples/qml/referenceexamples/adding example from Qt v6.x"""

from pathlib import Path
import sys

from PySide6.QtCore import QCoreApplication
from PySide6.QtQml import QQmlComponent, QQmlEngine

from person import Person  # noqa: F401


if __name__ == '__main__':
    app = QCoreApplication(sys.argv)

    engine = QQmlEngine()
    engine.addImportPath(Path(__file__).parent)
    component = QQmlComponent(engine)
    component.loadFromModule("People", "Main")

    person = component.create()
    if person:
        print(f"The person's name is {person.name}")
        print(f"They wear a {person.shoe_size} sized shoe")
    else:
        print(component.errors())
    del engine
    sys.exit(0)
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

from PySide6.QtCore import QObject, Property
from PySide6.QtQml import QmlElement

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


@QmlElement
class Person(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._name = ''
        self._shoe_size = 0

    @Property(str)
    def name(self):
        return self._name

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

    @Property(int)
    def shoe_size(self):
        return self._shoe_size

    @shoe_size.setter
    def shoe_size(self, s):
        self._shoe_size = s
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

import People

Person {
    name: "Bob Jones"
    shoe_size: 12
}
module People
typeinfo coercion.qmltypes
Main 1.0 Main.qml