如何使用PyQt5在qml中设置值?

时间:2018-04-19 20:56:09

标签: python pyqt qml pyqt5

从PyQt5我想将值写入qml。此值会动态更改。例如,它在矩形文本值中是从Pyqt5

提交的
abc

1 个答案:

答案 0 :(得分:2)

如果要从python修改QML属性,则必须创建一个继承自QObject且为qproperty的类,然后使用setContextProperty()将其导出到QML。

<强> 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

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    Text{
        anchors.fill: parent
        text:  obj.text
    }

}