python和qml混合编程,过程中免不了有很多需要交互数据和参数的情况,虽然现在项目基本完成,回过头来总结下参数传递,以防后期查阅,其中有不少借鉴的地方。主要还是以备后期查看。
一、QML显式的调用Python函数(无返回)
#!/usr/bin/env python
# qml-test1.py
'''
定义一个类,并继承QtCore.QObject对象,并使用@修饰符修饰pyqtSlot
创建rootContext对象,并使用setContextProperty(string, object)注册对象,
这样在QML中就可以调用这个函数了。
这个例子运行后,如果点击鼠标的话,会在控制台打印字符串。
'''
from PyQt5.QtQuick import QQuickView
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MyClass(QObject):
@pyqtSlot(str) # 输入参数为str类型
def outputString(self, string):
print(string)
@pyqtSlot(list) # list可以被识别
def outputlist(self,qmllist):
print(qmllist)
@pyqtSlot(QVariant) # dict不能
def outputdict(self,qmldict):
print(qmldict.toVariant(),type(qmldict.toVariant()))
if __name__ == '__main__':
app = QGuiApplication([])
path = 'test.qml' # 加载的QML文件
con = MyClass()
view = QQuickView()
view.engine().quit.connect(app.quit)
view.setSource(QUrl(path))
context = view.rootContext()
context.setContextProperty("con", con)
view.setFramePosition(QPoint(100,100))
view.show()
app.exec_()
//test.qml
import QtQuick 2.0
Rectangle {
width: 320; height: 240
color: "red"
Text {
id: txt
text: "Clicked btn"
font.pixelSize: 20
anchors.centerIn: parent
}
MouseArea {
id: mouse_area
anchors.fill: parent // 有效区域
onClicked: {
con.outputString("Hello, Python3") //QML显式的调用Python函数
con.outputlist(["Hello, Python3"]) //QML显式的调用Python函数
con.outputdict({"Hello": "Python3"}) //QML显式的调用Python函数
}
}
}
二、QML显式的调用Python函数(有返回)
#!/usr/bin/env python
# qml-test2.py
'''
这个例子跟上一个相类似,只是这次调用Python的函数具有返回值功能。
运行程序后,点击鼠标,左上角会显示数字30。
'''
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtQuick import *
from PyQt5.QtQml import *
class MyClass(QObject):
@pyqtSlot(int, result=str)
def returnValue(self, value):
return str(value + 10)
@pyqtSlot(int, result=list)
def returnList(self, value):
return [1, 2, 3]
# @pyqtSlot(int,result=QVariant)
# def returnDict(self, value):
# return QJsonDocument.fromJson(b'{"test": null}')
@pyqtSlot(result=QVariant)
def returnDict(self, ):
return {"a": 1, "b": 2} # 键必须是字符串
# @pyqtSlot(int,result=QVariant)
# def returnDict(self, value):
# return QJsonDocument.fromJson(b'{"test": null}')
# # return QVariant()
# # return QJsonValue()
if __name__ == '__main__':
app = QGuiApplication([])
path = 'test2.qml' # 加载的QML文件
con = MyClass()
view = QQuickView()
view.engine().quit.connect(app.quit)
view.setSource(QUrl(path))
context = view.rootContext()
context.setContextProperty("con", con)
view.show()
app.exec_()
// test2.qml
import QtQuick 2.0
Rectangle {
id: root
width: 320; height: 240
color: "lightgray"
Text {
id: txt
text: "Clicked me"
font.pixelSize: 20
anchors.centerIn: parent
}
Text {
id: txt1
text: "..."
font.pixelSize: 20
}
MouseArea {
id: mouse_area
anchors.fill: parent // 有效区域
onClicked: {
console.log("test...") // 控制台打印信息
txt1.text = con.returnValue(20) //QML显式的调用Python函数
console.log(con.returnList(20))
var data = con.returnDict(20)
for(var key in data){
var value = data[key]
console.log(key, ": ", value)
}
}
}
}
三、QML连接信号到Python
#!/usr/bin/env python
# qml-test3.py
'''
当QML触发事件的时候,发射一个信号给Python,此时Python调用一个函数。
先在QML中定义一个信号,
然后在捕获事件的时候,发射信号,
最后Python中创建一个rootObject对象,然后连接这个对象,
这个例子中,当点击鼠标的时候,控制台会打印信息。
'''
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def outputString(string):
print(string)
@pyqtSlot(list, result=list) # 并不会自动识别,还是需要toVariant()
def outputList(string):
print(string.toVariant())
def outputDict(string):
print(string.toVariant()) # 整数的键过来会自动变字符串
if __name__ == '__main__':
path = 'test3.qml' # 加载的QML文件
app = QGuiApplication([])
view = QQuickView()
view.engine().quit.connect(app.quit)
view.setSource(QUrl(path))
view.show()
# 需要信号连接
context = view.rootObject()
context.sendClicked1.connect(outputString) # 连接QML信号sendCLicked
context.sendClicked2.connect(outputList) # 连接QML信号sendCLicked
context.sendClicked3.connect(outputDict) # 连接QML信号sendCLicked
context.sendClicked31.connect(outputDict) # 连接QML信号sendCLicked
app.exec_()
// test3.qml
import QtQuick 2.0
Rectangle {
id: root
width: 320; height: 240
color: "lightgray"
signal sendClicked1(string str) // 定义信号
signal sendClicked2(var list) // 定义信号
signal sendClicked3(var dict) // 定义信号
signal sendClicked31(var dict) // 定义信号
Text {
id: txt
text: "Clicked me"
font.pixelSize: 20
anchors.centerIn: parent
}
MouseArea {
id: mouse_area
anchors.fill: parent //有效区域
onClicked: {
root.sendClicked1("Hello, Python3")//发射信号到Python
root.sendClicked2(["Hello, Python3"])//发射信号到Python
root.sendClicked3({"Hello":"Python3"})//发射信号到Python
root.sendClicked31({1:"Python3"})//发射信号到Python
}
}
}
四、把 python 类注册成 qml 类
qmlRegisterType(CameraOpencv,'MyCamera',1,0,'MyCustomOpenCVItem')
qml中直接使用
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.1
import MyCamera 1.0
Item{
id:root
property alias myCustomOpenCVItem: myCustomOpenCVItem
Rectangle{
color:"black"
anchors.fill: parent
MyCustomOpenCVItem{
id:myCustomOpenCVItem
objectName:"camera_win"
anchors.fill:parent
}
MouseArea{
anchors.fill: parent
onClicked: {
content.contentMiddle.myCustomOpenCVItem.save()
}
}
}
}
五、设置可在 qml 中用的属性
方法一:
self._goodsName = '' #当前商品名称
goodsNameChanged = pyqtSignal(str)
@pyqtProperty(str,notify=goodsNameChanged)
def goodsName(self):
return self._goodsName
@goodsName.setter
def goodsName(self, value):
self._goodsName = value
self.goodsNameChanged.emit(value)
方法二:
projectName = pyqtProperty(str, fget=getProjectValue, fset= setProjectValue, notify=projectNameChanged)
.qml 动态设置 component
function getLoader (){
switch (uploadStatus)
{
case "imgUploadFail":
return uploadFail
case "imgUploadOK":
return uploadOK
case "imgUploading":
return uploading
case "imgUploadReady":
return null
default:
return null
}
}
Loader{
id:currLoad
anchors.fill:parent
sourceComponent:getLoader()
}