当前位置: 首页 > news >正文

Pyside6联合QML实现消息弹窗提示

Pyside6联合QML实现消息弹窗提示

1.功能描述

Qt创建一个QWidget窗口,窗口中包含一个QLineEdit输入框,包含一个QPushButton按钮,输入框接收信息,点击按钮,显示QML定义的弹窗提示,提示内容为输入框接收的信息。

2.感谢

1.QFluentWidgets 一个基于 C++ Qt/PyQt/PySide 的 Fluent Design 风格组件库

2.QML弹窗提示

3.《PySide6/PyQt6快速开发与实战》-PySide6部分源代码

3.关键属性

1.Python通过Property定义一个变量,Property 是 PySide 中用于定义 Python 属性与 QML 交互的装饰器。当你使用 Property 装饰器时,你实际上是在创建一个 Qt 属性,它可以在 QML 和 Python 之间进行双向绑定,通过setter函数以及getter函数对变量进行赋值与读取,通过notify定义的信号触发getter函数,对变量进行取值。

2.Python中,定义QQmlApplicationEngine()引擎,通过引擎获取QML界面,通过元素设置的objectName获取需要的元素,调用元素页面中定义的方法以及获取元素中的属性。

4.代码

1.文件目录

2.PopWindow.qml

//PopWindow.qml
import QtQuick
import QtQuick.Controls 2.5
import QtQuick.Window 2.3Window{id: pop_windowvisible: falsecolor: "transparent"// 透明度opacity: 0// 取消边框flags:Qt.FramelessWindowsHint | Qt.ToolTip// 设置为非模态modality: Qt.NonModal//设置初始位置(外部设置会覆盖此设置)x: Screen.width - content_pop_window.widthy: 100//根据Loader设置大小width: content_loader.widthheight: content_loader.height//设置显示内容的变量property alias content_pop_window:content_loader.sourceComponentMouseArea{id:content_mouseanchors.fill: parenthoverEnabled: true}//加载内容的LoaderLoader{id:content_loaderanchors.centerIn:parent}// 设置出现后显示时间的计时器Timer{id:show_timerinterval: 2000repeat: trueonTriggered:{// 此函数在后面定义hideWindow();}}//设置出现显示动画ParallelAnimation{id: show_anim// 透明度动画NumberAnimation{target:pop_windowproperty: "opacity"from:pop_window.opacityto: 1duration:800}//位置移动动画NumberAnimation{target:pop_windowproperty: "x"//从当前值开始移动from: Screen.widthto: pop_window.x - content_loader.widthduration:800}onStarted:{pop_window.show()}//动画结束信号onFinished:{show_timer.start()}}//设置关闭显示动画ParallelAnimation{id: hide_anim// 透明度动画NumberAnimation{target:pop_windowproperty: "opacity"from:pop_window.opacityto: 0duration:800}//位置移动动画NumberAnimation{target:pop_windowproperty: "x"//从当前值开始移动from: pop_window.xto: Screen.widthduration:800}//动画结束之后关闭窗口onFinished:{show_timer.stop();pop_window.close();}}//显示弹窗function showWindow(){show_anim.start()}//隐藏弹窗function hideWindow(){show_anim.stop()hide_anim.start()}
}

3.main.qml

import QtQuick
import QtQuick.Controls 2.5
import QtQuick.Window 2.3
import Qt5Compat.GraphicalEffectsApplicationWindow {id: windowobjectName: "win"PopWindow{id:popobjectName: "popWin"// 设置初始位置,对PopWindow里面的x,y进行了覆盖x: get_screen_pixel(1, Screen.width) - get_screen_pixel(0.005, Screen.width)y: get_screen_pixel(0.13, Screen.height)content_pop_window:Rectangle{id:bk_rectangle// 根据文本内容自适应显示宽度width:text_id.contentWidth+110height:70radius:10color: Qt.rgba(0.8,0.8,0.8,0.8)Image {id: imgwidth: 60height: 60anchors.verticalCenter: parent.verticalCenteranchors.left: parent.leftanchors.leftMargin:6source: "info_icon.png"smooth: truevisible: false}Rectangle {id: img_maskwidth: img.widthheight: img.heightradius: 10color: "red"visible: false}OpacityMask {anchors.fill: imgsource: imgmaskSource: img_mask}Text{id:text_idanchors.verticalCenter: parent.verticalCenter// anchors.verticalCenterOffset: -16anchors.left:img.rightanchors.leftMargin:10font.pointSize:17text:qsTr("text: " + py_window.transfer_info)}MouseArea{anchors.fill:parent}}}// 为了适应不同的屏幕,需要使用百分比表示function get_screen_pixel(percent, sum_pixel){return percent * sum_pixel}
}

3.run.py

"""
@FileName:run.py
@Author:zgr
@Time:2025/4/17 21:41
@Description:
"""
import os
import sysfrom PySide6.QtCore import QObject, Property, Signal
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtWidgets import QWidget, QVBoxLayout, QApplication
from qfluentwidgets import PrimaryPushButton, LineEditapp = QApplication(sys.argv)
engine = QQmlApplicationEngine()class MainWindowViewModel(QWidget):def __init__(self, parent=None):super().__init__(parent)self.win_obj = Noneself.root_obj = None# 页面 部署输入框与按钮self.pop_btn = PrimaryPushButton()self.pop_btn.setObjectName("pop_window")self.pop_btn.setText("弹窗")self.pop_btn.clicked.connect(self.show_pop_window)self.info_edit = LineEdit()self.info_edit.setPlaceholderText("请输入弹窗信息")self.info_edit.setClearButtonEnabled(True)self.info_edit.setObjectName("info_edit")self.info_edit.textChanged.connect(self.set_transfer_info)# 垂直布局left_layout = QVBoxLayout(self)left_layout.addWidget(self.info_edit)left_layout.addWidget(self.pop_btn)self.init_qml()transfer_info_change = Signal()# transfer_info = Property(str, notify=transfer_info_change)@Property(str, notify=transfer_info_change)def transfer_info(self):return self.info_edit.text()def set_transfer_info(self):"""定义 setter 方法来触发信号:return:"""self.transfer_info_change.emit()def init_qml(self):"""绑定qml文件:return:"""# 把当前类添加到qml的上下文中engine.rootContext().setContextProperty('py_window', self)path = os.path.dirname(__file__) + os.sep + 'main.qml'engine.load(path)if not engine.rootObjects():sys.exit(-1)# 获取mql界面的元素self.root_obj = engine.rootObjects()[0]# popWin是qml窗口的objectName 获取到弹窗的窗口self.win_obj = self.root_obj.findChild(QObject, "popWin")def show_pop_window(self):"""弹窗:return:"""self.win_obj.showWindow()if __name__ == '__main__':win = MainWindowViewModel()win.show()sys.exit(app.exec())

5.总结

本文主要想描述的问题为Python与QML如何互相通信,借助一个消息弹窗的例子来展现,如有不到之处欢迎批评指正。

http://www.xdnf.cn/news/20413.html

相关文章:

  • 通过 Tailwind CSS 自定义样式 实现深色模式切换
  • Brain Stimulation | 状态依赖性刺激中的大脑网络动态:基于隐马尔可夫模型的EEG-TMS联合分析
  • 多态:面向对象编程的重要特性
  • CSS伪类
  • CSS 文件格式
  • 期货交易躲过AI捕杀—期货反向跟单策略
  • 基于PySide6与pyCATIA的圆柱体特征生成工具开发实战——NX建模之圆柱命令的参考与移植
  • 守护进程编程、GDB调试以及外网连接树莓派
  • 【数据结构】深入理解:完全二叉树中叶子节点与分支节点的数量关系推导
  • 每天学一个 Linux 命令(21):tree
  • Harmony5.0 设置应用全屏模式,隐藏导航栏和状态栏
  • 我的创作纪念日
  • HCIP-H12-821 核心知识梳理 (3)
  • 系统架构设计师:计算机组成与体系结构(如CPU、存储系统、I/O系统)高效记忆要点、知识体系、考点详解、、练习题并提供答案与解析
  • 4.3 熟悉字符串处理函数
  • 告别Feign:基于Spring 6.1 RestClient构建高可用声明式HTTP客户端
  • aop原理及场景
  • AI预测3D新模型百十个定位预测+胆码预测+去和尾2025年4月18日第56弹
  • 如何通过OTP动态口令登录Windows操作系统实现安全管控?安当SLA双因素认证的行业化解决方案
  • 《P2882 [USACO07MAR] Face The Right Way G》
  • AI Agent智能体是什么?如何使用?
  • Django 结合 Vue 实现简单管理系统的详解
  • vue3+axios下载哪后端返回错误信息并动态提示
  • 【学习笔记】Py网络爬虫学习记录(更新中)
  • thinkphp实现图像验证码
  • 2025年03月中国电子学会青少年软件编程(Python)等级考试试卷(一级)真题
  • DDS Discovery数据
  • PM2模块
  • AI专题(一)----NLP2SQL探索以及解决方案
  • std::unordered_set(C++)