目錄
一、Qml作為窗口引入
二、Qml作為控件引入(Qml根組件不能是window)
三、兩個(gè)問題①Q(mào)ml文件如何調(diào)用python函數(shù)②python代碼如何控制Qml元素。
一、Qml作為窗口引入
例:QWidget窗口中用按鈕打開和關(guān)閉Qml窗口
①Q(mào)Widget窗口
import sys
from pathlib import Path
from PySide6.QtCore import QObject, Slot
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtQuick import QQuickItem
from PySide6.QtWidgets import QApplication, QWidget, QPushButton
class TestWidget(QWidget):
def __init__(self, parent=None):
super(TestWidget, self).__init__(parent)
self.button_open = QPushButton(self)
self.button_open.setText("打開Qml窗口")
self.button_open.setGeometry(0, 100, 100, 50)
self.button_open.clicked.connect(self.handle_button_open_click)
self.button_close = QPushButton(self)
self.button_close.setText("關(guān)閉Qml窗口")
self.button_close.setGeometry(100, 100, 100, 50)
self.button_close.clicked.connect(self.handle_button_close_click)
# 打開Qml窗口
def handle_button_open_click(self):
self.widget = LoginQuickWidget()
# 關(guān)閉Qml窗口
def handle_button_close_click(self):
if hasattr(self, 'widget') and self.widget:
del self.widget
if __name__ == '__main__':
app = QApplication([])
widget = TestWidget()
widget.show()
app.exec()
②Qml窗口
注意:此處是直接引入qml文件。如果是從qrc資源文件中引入qml,則直接QQmlApplicationEngine.load即可????????
文章來源:http://www.zghlxwxcb.cn/news/detail-562437.html
# 槽函數(shù)類(一個(gè)承載槽函數(shù)的容器類)
class Slots(QObject):
def __init__(self, objects):
self.objects = objects
super().__init__()
@Slot(str, result=None)
def set_text_msg(self, msg):
# 獲取qml中的Text對(duì)象
child = self.objects[0].findChild(QQuickItem, "text1")
# 獲取對(duì)象屬性
p = child.property("text")
# 設(shè)置對(duì)象屬性
child.setProperty("text", p + msg)
@Slot(result=str)
def get_text_msg(self):
return "皎氯"
"""
這種方式是以Qml作為窗口來使用。所有的邏輯UI都由Qml來完成。python提供可以調(diào)用數(shù)據(jù)的API即可。
"""
class LoginQuickWidget:
def __init__(self):
# 初始化UI
self.engine = QQmlApplicationEngine()
qml_file = Path(__file__).resolve().parent / "login.qml"
# 加載qml文件
self.engine.load(qml_file)
if not self.engine.rootObjects():
sys.exit(-1)
# qml對(duì)象集合
objects = self.engine.rootObjects()
# 實(shí)例化槽函數(shù)
self.slots = Slots(objects)
# 注入槽函數(shù)
self.engine.rootContext().setContextProperty('slots', self.slots)
③Qml文件文章來源地址http://www.zghlxwxcb.cn/news/detail-562437.html
/**************************QML文件**************************/
import QtQuick
import QtQuick.Window
import QtQuick.Controls 6.3
import QtQuick.Layouts 6.3
import QtQuick.Controls.Windows 6.0
//主窗口
Window {
width: 800
height: 400
visible: true
title: qsTr("測試窗口")
Image {
id:background_image
anchors.fill: parent
fillMode: Image.PreserveAspectCrop
source: "http://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg"
antialiasing: true
}
//文本展示框
Text {
id: text1
//用于python獲取此對(duì)象
objectName:"text1"
x: 300
y: 20
width: 200
height: 34
text: qsTr("初始值")
font.pixelSize: 12
}
//一:通過JavaScript控制UI邏輯
Button {
id: button
x: 125
y: 179
width: 125
height: 29
text: qsTr("調(diào)用JavaScript方法")
//點(diǎn)擊事件
onClicked: {
change()
}
//JavaScript函數(shù)
function change(){
var date = new Date();
text1.text=qsTr(date.getFullYear()+"年"+(date.getMonth() + 1)+"月"+date.getDate()+"日"+date.getHours()+"時(shí)"+date.getMinutes()+"分"+date.getSeconds()+"秒")
}
}
//二:通過Python控制UI邏輯(不推薦,因?yàn)橐鯱I與業(yè)務(wù)邏輯分離;槽函數(shù)相當(dāng)于于ajax請(qǐng)求來獲取數(shù)據(jù),而不是去控制UI本身)
Button {
id: button1
x: 325
y: 179
width: 125
height: 29
text: qsTr("調(diào)用Python設(shè)置屬性")
//點(diǎn)擊事件
onClicked: {
//調(diào)用注入的槽函數(shù),使用槽函數(shù)改變視圖
slots.set_text_msg("小小改變")
}
}
//三:通過Python獲取數(shù)據(jù),JavaScript渲染UI(推薦方式)
Button {
id: button2
x: 525
y: 179
width: 125
height: 29
text: qsTr("調(diào)用Python獲取數(shù)據(jù)")
//點(diǎn)擊事件
onClicked: {
//調(diào)用注入的槽函數(shù),使用槽函數(shù)獲取數(shù)據(jù)
var msg=slots.get_text_msg()
//利用JS進(jìn)行渲染
text1.text=qsTr(msg)
}
}
}
二、Qml作為控件引入(Qml根組件不能是window)
from PySide6.QtCore import QUrl, Slot, QObject
from PySide6.QtQuick import QQuickItem
from PySide6.QtQuickWidgets import QQuickWidget
from PySide6.QtWidgets import QWidget, QApplication, QVBoxLayout, QPushButton
# 槽函數(shù)類(一個(gè)承載槽函數(shù)的容器類)
class Slots(QObject):
def __init__(self, obj):
super(Slots, self).__init__()
self.obj = obj
@Slot(str, result=None)
def set_text_msg(self, msg):
# 獲取qml中的Text對(duì)象
child = self.obj.findChild(QQuickItem, "text1")
# 獲取對(duì)象屬性
p = child.property("text")
# 設(shè)置對(duì)象屬性
child.setProperty("text", p + msg)
@Slot(result=str)
def get_text_msg(self):
return "皎氯"
class TestQWidget(QWidget):
def __init__(self, parent=None):
super(TestQWidget, self).__init__(parent)
self.resize(800, 300)
# 垂直布局
self.layout = QVBoxLayout(self)
# OK按鈕
self.button = QPushButton("OK")
self.button.clicked.connect(lambda: print("OK"))
self.layout.addWidget(self.button)
# QML控件
self.qml_widget = QQuickWidget()
# 設(shè)置縮放模式
self.qml_widget.setResizeMode(QQuickWidget.ResizeMode.SizeRootObjectToView)
# 向QML中傳入數(shù)據(jù)(必須在setSource之前傳入)
self.qml_widget.rootContext().setContextProperty("obj", '張良')
self.qml_widget.setSource(QUrl("test2.qml"))
# 獲取QML中的對(duì)象(必須在setSource之后)
self.root_object: QQuickItem = self.qml_widget.rootObject()
# 實(shí)例化槽函數(shù)
self.slots = Slots(self.root_object)
# 注入槽函數(shù)
self.qml_widget.rootContext().setContextProperty('slots', self.slots)
# 獲取對(duì)象
child: QQuickItem = self.root_object.findChild(QQuickItem, "text1")
# 獲取對(duì)象屬性
print(child.property("text"))
# 加入布局
self.layout.addWidget(self.qml_widget)
if __name__ == '__main__':
app = QApplication([])
widget = TestQWidget()
widget.show()
app.exec()
import QtQuick
import QtQuick.Window
import QtQuick.Controls 6.3
import QtQuick.Layouts 6.3
import QtQuick.Controls.Windows 6.0
Rectangle {
id:root
color: "yellow"
radius:10
//背景圖
Image {
id:background_image
anchors.fill: parent
fillMode: Image.PreserveAspectCrop
source: "http://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg"
antialiasing: true
}
//文本展示框
Text {
id: text1
//用于python獲取此對(duì)象
objectName:"text1"
x: 300
y: 20
width: 200
height: 34
text: qsTr(obj)
font.pixelSize: 12
}
//一:通過JavaScript控制UI邏輯
Button {
id: button
x: 125
y: 179
width: 125
height: 29
text: qsTr("調(diào)用JavaScript方法")
//點(diǎn)擊事件
onClicked: {
change()
}
//JavaScript函數(shù)
function change(){
var date = new Date();
text1.text=qsTr(date.getFullYear()+"年"+(date.getMonth() + 1)+"月"+date.getDate()+"日"+date.getHours()+"時(shí)"+date.getMinutes()+"分"+date.getSeconds()+"秒")
}
}
//二:通過Python控制UI邏輯(不推薦,因?yàn)橐鯱I與業(yè)務(wù)邏輯分離;槽函數(shù)相當(dāng)于于ajax請(qǐng)求來獲取數(shù)據(jù),而不是去控制UI本身)
Button {
id: button1
x: 325
y: 179
width: 125
height: 29
text: qsTr("調(diào)用Python設(shè)置屬性")
//點(diǎn)擊事件
onClicked: {
//調(diào)用注入的槽函數(shù),使用槽函數(shù)改變視圖
slots.set_text_msg("小小改變")
}
}
//三:通過Python獲取數(shù)據(jù),JavaScript渲染UI(推薦方式)
Button {
id: button2
x: 525
y: 179
width: 125
height: 29
text: qsTr("調(diào)用Python獲取數(shù)據(jù)")
//點(diǎn)擊事件
onClicked: {
//調(diào)用注入的槽函數(shù),使用槽函數(shù)獲取數(shù)據(jù)
var msg=slots.get_text_msg()
//利用JS進(jìn)行渲染
text1.text=qsTr(msg)
}
}
}
三、3個(gè)問題①Q(mào)ml文件如何調(diào)用python函數(shù)②python代碼如何控制Qml元素。③python如何執(zhí)行Qml中的函數(shù)。
到了這里,關(guān)于Qt第十六章:QWidget與QML混合開發(fā)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!