如何使用 PySide2 在 qml 中设置值? [英] How to set values in qml using PySide2?

查看:56
本文介绍了如何使用 PySide2 在 qml 中设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 PySide2 我想将值写入 qml.此值动态更改.

From PySide2 i want to write values into qml. This values change dynamically.

此处为 PyQt5 示例:如何使用 PyQt5 在 qml 中设置值?

For PyQt5 example here: How to set values in qml using PyQt5?

main.py:

import sys

from PySide2.QtCore import QObject, Signal, Property, QUrl, QTimer, QDateTime
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

class Foo(QObject):
    textChanged = Signal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self._text = ""

    @Property(str, notify=textChanged)
    def text(self):
        return self._text

    @text.setter
    def text(self, value):
        if self._text == value:
            return
        self._text = value
        self.textChanged.emit()


def update_value():
    obj.text = "values from PyQt5 :-D : {}".format(QDateTime.currentDateTime().toString())

if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    obj = Foo()
    timer = QTimer()
    timer.timeout.connect(update_value)
    timer.start(100)
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("obj", obj)
    engine.load(QUrl("main.qml"))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

main.qml:

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    id: parwin
    visible: true
    width: 640
    height: 480
    Text{
        anchors.fill: parent
        text:  obj.text
    }

}

我有错误:

main.qml:11:9: Unable to assign [undefined] to QString
main.qml:11: TypeError: Cannot read property 'text' of null

告诉我我的错误在哪里?

Tell me where is my mistake?

推荐答案

PySide2 的 setter 好像有 bug,所以没有正确注册 Property,解决方案是创建不同名称的 setter 和 getter 并使用Property() 单独暴露它:

It seems that PySide2 has a bug with the setter so it does not register the Property correctly, the solution is to create a setter and getter with different names and use Property() separately to expose it:

# ...

class Foo(QObject):
    textChanged = Signal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self._text = ""

    def get_text(self):
        return self._text

    def set_text(self, value):
        if self._text == value:
            return
        self._text = value
        self.textChanged.emit()

    text = Property(str, fget=get_text, fset=set_text, notify=textChanged)

# ...

这篇关于如何使用 PySide2 在 qml 中设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆