How can bind the buttons I create in a .qml script to python PyQt5 code?
example: python:
import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
if __name__ == "__main__":
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("main", engine)
engine.load('test.qml')
win = engine.rootObjects()[0]
win.show()
sys.exit(app.exec_())
qml:
import QtQuick 2.2
import QtQuick.Window 2.1
import QtQuick.Controls 1.2
import QtQuick.Dialogs 1.1
ApplicationWindow {
title: qsTr("Test Invoke")
width: 200
height: 100
Button{
y : 70
text : "About"
onClicked: {
print('Hello')
}
}
}
How can I do something with Python when the button is clicked? Also: Does anyone has a good resource of examples or doc. about pyqt + qml (qt quick)?
The key difference in the two versions — in fact the entire reason PySide2 exists — is licensing. PyQt5 is available under a GPL or commercial license, and PySide2 under a LGPL license.
You can purchase the commercial version of PyQt here. More information about licensing can be found in the License FAQ. PyQt does not include a copy of Qt. You must obtain a correctly licensed copy of Qt yourself.
PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. A GUI application consists of Front-end and Back-end.
If you name the button, you can connect to its onClick signal, or to a custom signal that it emits in onClicked
. Example:
ApplicationWindow {
title: qsTr("Test Invoke")
width: 200
height: 100
Button {
signal messageRequired
objectName: "myButton"
y : 70
text : "About"
onClicked: messageRequired()
}
}
Note the signal in Button and the objectName property. Then the Python code just before exec
could be for example:
def myFunction():
print 'handler called'
button = win.findChild(QObject, "myButton")
button.messageRequired.connect(myFunction)
button.clicked.connect(myFunction) # works too
Note that in the Button above, onClicked
just emits the messageRequired
signal, so it is better to drop the custom signal and connect to clicked
directly. Both onClicked()
and any slots connected to clicked
will get called when you click button.
There is another solution which uses a Python model (QObject) in QML.
Python
engine = QQmlApplicationEngine()
engine.load("main.qml")
class Greeter(QObject):
@pyqtSlot(str)
def sayHello(self, name):
print("Hello, " + name)
ctx = engine.rootContext()
ctx.setContextProperty("greeter", Greeter())
QML
Button {
onClicked: {
greeter.sayHello("Alice")
}
}
Ref.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With