【问题标题】:How to set values in qml using PySide2?如何使用 PySide2 在 qml 中设置值?
【发布时间】:2020-04-21 03:24:37
【问题描述】:

我想从 PySide2 将值写入 qml。该值会动态变化。

此处以 PyQt5 为例: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

告诉我我的错误在哪里?

【问题讨论】:

    标签: python qml pyside2


    【解决方案1】:

    看来PySide2的setter有bug所以没有正确注册Property,解决方法是创建一个不同名字的setter和getter,分别使用Property()来暴露:

    # ...
    
    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)
    
    # ...

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 2019-08-26
      • 2019-02-14
      • 2018-12-06
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多