/**************************QML文件**************************/
import QtQuick
import QtQuick.Window
import QtQuick.Controls 6.3
import QtQuick.Layouts 6.3
import QtQuick.Controls.Windows 6.0
//主窗口
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello EveryBody")
//文本展示框
Text {
id: text1
//用于python获取此对象
objectName:"text1"
x: 125
y: 119
width: 131
height: 34
text: qsTr("Text")
font.pixelSize: 12
}
//一:通过JavaScript控制UI逻辑
Button {
id: button
x: 125
y: 179
width: 125
height: 29
text: qsTr("调用JavaScript")
//点击事件
onClicked: {
change()
}
//JavaScript函数
function change(){
var date = new Date();
text1.text=qsTr(date.getFullYear()+"年"+(date.getMonth() + 1)+"月"+date.getDate()+"日"+date.getHours()+"时"+date.getMinutes()+"分"+date.getSeconds()+"秒")
}
}
//二:通过Python控制UI逻辑(不推荐,因为要做UI与业务逻辑分离;槽函数相当于于ajax请求来获取数据,而不是去控制UI本身)
Button {
id: button1
x: 325
y: 179
width: 125
height: 29
text: qsTr("调用Python")
//点击事件
onClicked: {
//调用注入的槽函数,使用槽函数改变视图
slots.set_text_msg("小小改变")
}
}
//三:通过Python获取数据,JavaScript渲染UI(推荐方式)
Button {
id: button2
x: 525
y: 179
width: 125
height: 29
text: qsTr("调用Python获取数据")
//点击事件
onClicked: {
//调用注入的槽函数,使用槽函数获取数据
var msg=slots.get_text_msg()
//利用JS进行渲染
text1.text=qsTr(msg)
}
}
}
import sys
from pathlib import Path
from PySide6.QtCore import QObject, Slot
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtQuick import QQuickView, QQuickItem
# 槽函数类(一个承载槽函数的容器类)
class Slots(QObject):
def __init__(self, objects):
self.objects = objects
super().__init__()
@Slot(str, result=None)
def set_text_msg(self, msg):
# 获取qml中的Text对象
child = self.objects[0].findChild(QQuickItem, "text1")
# 获取对象属性
p = child.property("text")
# 设置对象属性
child.setProperty("text", p + msg)
@Slot(result=str)
def get_text_msg(self):
return "皎氯"
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
qml_file = Path(__file__).resolve().parent / "main.qml"
# 加载qml文件
engine.load(qml_file)
if not engine.rootObjects():
sys.exit(-1)
# qml对象集合
objects = engine.rootObjects()
# 实例化槽函数
slots = Slots(objects)
# 注入槽函数
engine.rootContext().setContextProperty('slots', slots)
# 开启循环
sys.exit(app.exec())
还没有评论,来说两句吧...