Python 如何使用PySide2在qml中设置值?
我想从PySide2将值写入qml。这个值是动态变化的 对于此处的PyQt5示例: main.py:Python 如何使用PySide2在qml中设置值?,python,qml,pyside2,Python,Qml,Pyside2,我想从PySide2将值写入qml。这个值是动态变化的 对于此处的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)
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
告诉我我的错误在哪里?PySide2似乎在setter中有一个bug,因此它没有正确注册属性,解决方案是创建一个具有不同名称的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)
# ...
#。。。
Foo类(QObject):
textChanged=信号()
def uuu init uuu(self,parent=None):
QObject.\uuuuu init\uuuuu(自,父)
self._text=“”
def get_文本(自身):
返回self.\u文本
def set_文本(自身、值):
如果self.\u text==值:
返回
self.\u text=值
self.textChanged.emit()
text=属性(str,fget=get\u text,fset=set\u text,notify=textChanged)
#…