有2种方法:
一、 QML中定义一个信号,连接Python里的函数;
QML的信号连接Python的函数
QML:
首先在QML中定义一个信号,这里的信号传递一个字符串给函数(信号可带参数也可不带):
signal mySignal(string my_string)
然后在click中发射这个信号:
onClicked:{ root.mySignal("hello world") }
Python:
使用QML里的信号连接Python里的函数:
engine.rootObjects()[0].mySignal.connect(my_func) # 这里的mySignal是在QML里定义的
完整代码:
QML:
import QtQuick 2.12 import QtQuick.Controls 2.12 ApplicationWindow { id: root width: 250 height: 500 visible: true signal mySignal(string my_string) MouseArea { id: mouse_area anchors.fill: parent onClicked: { root.mySignal("hello world") } } }
Python:
from PyQt5.QtCore import QObject from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine import sys class MyWindow(QObject): def __init__(self): super().__init__() self.engine = QQmlApplicationEngine() self.engine.load('qml-test.qml') # root signal my_obj = self.engine.rootObjects()[0] my_obj.mySignal.connect(self.my_func) def my_func(self,my_string): print(my_string) if __name__ == '__main__': app = QGuiApplication(sys.argv) window = MyWindow() sys.exit(app.exec())
二、 Python中定义一个类及槽函数,在QML中使用这个槽函数
首先需要在Python里定义一个类,在类里写一个槽函数:
class Person(QObject): def __init__(self): super().__init__() @pyqtSlot() # 注意是槽函数! def begin(self): print('begin')
然后通过setContextProperty将这个类设置为上下文的一个属性值:
person = Person() engine.rootContext().setContextProperty('person',person)
完整代码:
Python:
from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtCore import QObject,pyqtSlot import sys class Person(QObject): def __init__(self): super().__init__() @pyqtSlot() # 注意是槽函数! def begin(self): print('begin') if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() person = Person() engine.rootContext().setContextProperty('person',person) engine.load('qml-test.qml') sys.exit(app.exec())
QML:
import QtQuick 2.12 import QtQuick.Controls 2.12 ApplicationWindow { id: root width: 250 height: 500 visible: true Button{ text:qsTr("begin") onClicked: { person.begin() } } }