簡體   English   中英

如何使用 PySide2 在 qml 中設置值?

[英]How to set values in qml using PySide2?

從 PySide2 我想將值寫入 qml。 該值動態變化。

對於此處的 PyQt5 示例: How to set values in qml using PyQt5?

主要.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_())

主.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

告訴我我的錯誤在哪里?

看來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)

# ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM