如何使用PySide2将designer设计的ui文件加载到Python类上鼠标拖拽显示路径

应用场景:

designer快速设计好UI文件后,需要增加一些特别的界面功能,如文件拖拽显示文件路径功能。

方法如下:

python 复制代码
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtUiTools import loadUiType

Ui_MainWindow, _ = loadUiType('mainwindow.ui')

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.setAcceptDrops(True)  # ==> 设置窗口支持拖动(必须设置)
    #鼠标拖入事件
    def dragEnterEvent(self, event):

        file = event.mimeData().urls()[0].toLocalFile()  # ==> 获取文件路径
        self.label.setText(file)    
        # 鼠标放开函数事件
        event.accept()
        
if "__main__" == __name__:
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

效果如下图:

相关推荐
cup113 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi005 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵7 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf8 小时前
Agent 流程编排
后端·python·agent
copyer_xyf8 小时前
Agent RAG
后端·python·agent
copyer_xyf8 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf9 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏