pyqt5与qml 传递字典dict 和列表list
网上都是那一篇基本类型的 , 死活找不到正确的 , 希望这篇大家都能看到 .
一
#!/usr/bin/env python
# qml-test1.py
'''
(1)QML显式的调用Python函数
定义一个类,并继承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函数
}
}
}
二
#!/usr/bin/env python
# qml-test2.py
'''
(2)QML显式的调用Python函数,并有返回
这个例子跟上一个相类似,只是这次调用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)
}
}
}
}
三
#!/usr/bin/env python
# qml-test3.py
'''
(3)QML连接信号到Python
当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
}
}
}