QML使用Python的函数过程解析
有2种方法:
一、QML中定义一个信号,连接Python里的函数;
这里的函数不用特意指明为槽函数,普通函数即可。
QML的信号连接Python的函数
QML:
首先在QML中定义一个信号,这里的信号传递一个字符串给函数(信号可带参数也可不带):
signalmySignal(stringmy_string)
然后在click中发射这个信号:
onClicked:{
root.mySignal("helloworld")
}
Python:
使用QML里的信号连接Python里的函数:
engine.rootObjects()[0].mySignal.connect(my_func)#这里的mySignal是在QML里定义的
完整代码:
QML:
importQtQuick2.12
importQtQuick.Controls2.12
ApplicationWindow{
id:root
width:250
height:500
visible:true
signalmySignal(stringmy_string)
MouseArea{
id:mouse_area
anchors.fill:parent
onClicked:{
root.mySignal("helloworld")
}
}
}
Python:
fromPyQt5.QtCoreimportQObject
fromPyQt5.QtGuiimportQGuiApplication
fromPyQt5.QtQmlimportQQmlApplicationEngine
importsys
classMyWindow(QObject):
def__init__(self):
super().__init__()
self.engine=QQmlApplicationEngine()
self.engine.load('qml-test.qml')
#rootsignal
my_obj=self.engine.rootObjects()[0]
my_obj.mySignal.connect(self.my_func)
defmy_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里定义一个类,在类里写一个槽函数:
classPerson(QObject):
def__init__(self):
super().__init__()
@pyqtSlot()#注意是槽函数!
defbegin(self):
print('begin')
然后通过setContextProperty将这个类设置为上下文的一个属性值:
person=Person()
engine.rootContext().setContextProperty('person',person)
QML文件里不需特别设置,直接调用函数即可。
完整代码:
Python:
fromPyQt5.QtGuiimportQGuiApplication
fromPyQt5.QtQmlimportQQmlApplicationEngine
fromPyQt5.QtCoreimportQObject,pyqtSlot
importsys
classPerson(QObject):
def__init__(self):
super().__init__()
@pyqtSlot()#注意是槽函数!
defbegin(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:
importQtQuick2.12
importQtQuick.Controls2.12
ApplicationWindow{
id:root
width:250
height:500
visible:true
Button{
text:qsTr("begin")
onClicked:{
person.begin()
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。