【问题标题】:How to set values in qml using PyQt5?如何使用 PyQt5 在 qml 中设置值?
【发布时间】:2018-09-30 11:46:29
【问题描述】:

我想从 PyQt5 将值写入 qml。该值动态变化。例如它在矩形文本中的值是从 Pyqt5 提交的

    Rectangle {
        width: 75
        height: 75
        text { values from PyQt5 }
    }    

【问题讨论】:

    标签: python pyqt qml pyqt5


    【解决方案1】:

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

    ma​​in.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_())
    

    ma​​in.qml

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

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2017-07-24
      • 2019-06-13
      相关资源
      最近更新 更多