Here is a small example of working with QML QtQuick (Signals and slots).
Some explanations in the text of the program.
Try it:
Button.py
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
class Main(QObject):
def __init__(self):
QObject.__init__(self)
# signal sending string
# necessarily give the name of the argument through arguments=['text1']
# otherwise it will not be possible to pick it up in QML
textResult = pyqtSignal(str, arguments=['text1'])
@pyqtSlot(str)
def text1(self, arg1):
# do something with the text and emit a signal
arg1 = arg1.upper()
self.textResult.emit(arg1)
if __name__ == "__main__":
import sys
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
main = Main()
engine.rootContext().setContextProperty("main", main)
engine.load("Button.qml")
engine.quit.connect(app.quit)
sys.exit(app.exec_())
Button.qml
import QtQuick 2.7
//import QtQuick.Window 2.1
import QtQuick.Controls 1.4
//import QtQuick.Dialogs 1.1
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
title: qsTr("Test Invoke")
width: 400
height: 100
color: "whitesmoke"
GridLayout {
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.margins: 9
columns: 4
rows: 2
rowSpacing: 10
columnSpacing: 10
Text {
text: qsTr("Enter text")
}
// Text input box
TextField {
id: firstString
}
Button {
height: 40
Layout.fillWidth: true
text: qsTr("Send text for processing")
Layout.columnSpan: 2
onClicked: {
// call the slot to process the text
main.text1(firstString.text)
}
}
Text {
text: qsTr("Result")
}
// Here we see the result of text processing
Text {
id: textResult
}
}
// Here we take the result of text processing
Connections {
target: main
// Signal Handler
onTextResult: {
// text1 - was given through arguments=['text1']
textResult.text = text1
}
}
}
