gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:22:05 29 4
gpt4 key购买 nike

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

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

最佳答案

如果你想从 python 修改 QML 属性,你必须创建一个继承自 QObject 的类,这是一个 qproperty,然后使用 将它导出到 QML >setContextProperty().

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

}

关于python - 如何使用 PyQt5 在 qml 中设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49930114/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com