Python-PyQt5-图形可视化界面(5)--打开文件或文件夹--QFileDialog

转载至:https://www.jianshu.com/p/98e8218b2309

QFileDialog是一个打开文件或者文件夹选择对话框。
类似于我们平时上传文件选择文件的界面

打开文件有以下3种:
1、单个文件打开 QFileDialog.getOpenFileName()
2、多个文件打开 QFileDialog.getOpenFileNames()
3、打开文件夹 QFileDialog.getExistingDirectory()

QFileDialog::getOpenFileName (QWidget * parent = 0,
const QString & caption = QString(),  
const QString & dir = QString(),   
const QString & filter = QString(),  
QString * selectedFilter = 0,  
Options options = 0 )
  • parent,用于指定父组件。注意,很多Qt组件的构造函数都会有这么一个parent参数,并提供一个默认值0;在一般成员函数中写作this,但是要记住如果是在main函数中一定要写NULL。
  • caption,是对话框的标题。
  • ​dir,是对话框显示时默认打开的目录。"." 代表程序运行目录,"/" 代表当前盘符的根目录。如果不明确选择,只需要返回绝对路径也可以这样写。​ QDir dir;dir.absolutePath()。这个参数是最不好理解的。
  • ​filter,是对话框的后缀名过滤器。如果显示该目录下的全部文件可以“.”需要什么自己修改后面的*。
  • selectedFilter,是默认选择的过滤器。
  • options,是对话框的一些参数设定,比如只显示文件夹等等,它的取值是enum QFileDialog::Option,每个选项可以使用 | 运算组合起来。

通常来说,QFileDialog需要绑定到一个button组件上面
其实QFileDialog就是一个事件,需要button来触发。
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Ui_MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(Ui_MainWindow,self).__init__()
        self.setupUi(self)
        self.retranslateUi(self)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(386, 127)
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.retranslateUi(MainWindow)

        self.pushButton = QtWidgets.QPushButton(self.centralWidget)
        self.pushButton.setGeometry(QtCore.QRect(190, 90, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setText("打开")
        MainWindow.setCentralWidget(self.centralWidget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.pushButton.clicked.connect(self.openfile)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "一颗数据小白菜"))


    def openfile(self):
        openfile_name = QFileDialog.getOpenFileName(self,'选择文件','','Excel files(*.xlsx , *.xls)')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

注意:QFileDialog.getOpenFileName(self,'选择文件','','Excel files(*.xlsx , *.xls)')中的self参数需要是具有QtWidgets.QMainWindow类的参数




原文地址:https://www.cnblogs.com/caiya/p/15104266.html