[英]How to set values in qml using PyQt5?
From PyQt5 i want to write values into qml. 我想从PyQt5将值写入qml。 This values change dynamically. 该值动态变化。 For example it in rectangle text value is filed from Pyqt5 例如,它在矩形文本值是从Pyqt5归档的
Rectangle {
width: 75
height: 75
text { values from PyQt5 }
}
If you want to modify a QML property from python you must create a Class that inherits from QObject
and that is a qproperty
, then export it to QML using setContextProperty()
. 如果要从python修改QML属性,则必须创建一个从QObject
继承的类,它是一个qproperty
,然后使用setContextProperty()
将其导出到QML。
main.py main.py
import sys
from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, QUrl, QTimer, QDateTime
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
class Foo(QObject):
textChanged = pyqtSignal()
def __init__(self, parent=None):
QObject.__init__(self, parent)
self._text = ""
@pyqtProperty(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 main.qml
import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
Text{
anchors.fill: parent
text: obj.text
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.