QML使用Python的函式過程解析
阿新 • • 發佈:2020-01-09
有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中使用這個槽函式
在QML中呼叫Python中的槽函式
首先需要在Python裡定義一個類,在類裡寫一個槽函式:
class Person(QObject): def __init__(self): super().__init__() @pyqtSlot() # 注意是槽函式! def begin(self): print('begin')
然後通過setContextProperty將這個類設定為上下文的一個屬性值:
person = Person() engine.rootContext().setContextProperty('person',person)
QML檔案裡不需特別設定,直接呼叫函式即可。
完整程式碼:
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() } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。