I'm trying to do a simple task with PyQt5 and QML: have a button that changes a label when it is clicked. I've been able to execute a python function when the button is pressed, but I don't know how to change the text in the label.
This is a minimal example:
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
}
}
}
How can I change the text of the label to "Next", for instance?
Note: This is not a duplicate of QML not taking ownership of object received from PyQt slot. That question is about ownership of the data between Python and QML, and doesn't answer this question.