【发布时间】:2018-10-11 11:01:11
【问题描述】:
我正在尝试使用 PyQt5 和 QML 完成一个简单的任务:有一个按钮可以在单击时更改标签。按下按钮时我已经能够执行python函数,但是我不知道如何更改标签中的文本。
这是一个最小的例子:
main.py
from PyQt5.QtWidgets import *
from PyQt5.QtQml import *
from PyQt5.QtCore import *
import sys
def onClicked():
print('handler called')
if __name__ == '__main__':
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load(QUrl('main.qml'))
win = engine.rootObjects()[0]
button = win.findChild(QObject, 'myButton')
button.messageRequired.connect(onClicked)
sys.exit(app.exec_())
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.3
import QtQuick.Window 2.3
ApplicationWindow{
title: qsTr('Quomodo')
id: mainWindow
width: 480
height: 640
visible: true
Column {
anchors.horizontalCenter: parent.horizontalCenter
spacing: 8
padding: 8
Button {
signal messageRequired
objectName: "myButton"
text: qsTr("Work")
highlighted: true
onClicked: messageRequired()
}
Label {
text: qsTr("Time")
anchors.horizontalCenter: parent.horizontalCenter
}
}
}
例如,如何将标签的文本更改为“下一步”?
注意:这不是QML not taking ownership of object received from PyQt slot 的副本。这个问题是关于 Python 和 QML 之间数据的所有权问题,不回答这个问题。
【问题讨论】: