简体   繁体   中英

How to set values in qml using PySide2?

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

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
    }

}

i got error:

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?

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 = ""

    
        return self._text

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

    

# ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM