PyQt5学习笔记-06

Qt中的QFileDialog

Posted by hmoytx on May 4, 2018

简介

Qt中为了支持读写块数据,提供了一个共同的实现和一个通用接口。 QTIO 在QT中读写文件需要用到QFile,但是在python中可以直接利用python的的文件读写完成。 这里主要讲的是利用QFileDialog,得到文件绝对路径。

具体代码

import sys
from PyQt5 import QtWidgets, QtCore
from demo import Ui_Form


class mainwindow(QtWidgets.QWidget, Ui_Form):

    def __init__(self):
        super(mainwindow, self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.msg)
    
    def msg(self):
        fileneme, filetype = QtWidgets.QFileDialog.getOpenFileName(self,
                                                            "选取文件",  #标题
                                                            "C:/User/Administrator/Desktop/python", #路径
                                                            "All Files(*);;Python Files(*.py)" #文件类型 注意用;;分隔
                                                            )
        
        f = open(fileneme,"r")
        res = f.read()
        self.tb.setText(res)

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    window = mainwindow()
    window.show()
    sys.exit(app.exec_())

运行结果如下 result_1 result_2

注意

常见的有以下几种操作,参数都是一致的,根据不同需求选用不同的框 单个文件打开 QFileDialog.getOpenFileName() 返回一个路径 多个文件打开 QFileDialog.getOpenFileNames() 返回文件绝对路径和文件类型 文件夹选取 QFileDialog.getExistingDirectory() 文件列表和类型 文件保存 QFileDialog.getSaveFileName()