PyQt5:QFileDialog文件对话框(22)

时间:2021-02-07 23:03:44

学习《PyQt4入门指南 PDF中文版.pdf 》笔记

PyQt5:QFileDialog文件对话框(22)

文件对话框允许用户选择文件或者文件夹,被选择的文件可以进行读或写操作。

<span style="font-size:12px;">#!/usr/bin/python
# openfiledialog.py

from PyQt5.QtWidgets import QApplication, QAction, QFileDialog, QTextEdit
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon

class OpenFile(QtWidgets.QMainWindow):
def __init__(self, parent= None):
QtWidgets.QWidget.__init__(self)

self.setGeometry(300, 300, 150, 110)
self.setWindowTitle('OpenFile')
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)

self.statusBar()
self.setFocus()

exit = QAction(QIcon('icons/Blue_Flower.ico'), 'Open', self)
exit.setShortcut('Ctrl+O')
exit.setStatusTip('Open new file')

exit.triggered.connect(self.showDialog)

menubar = self.menuBar()
file = menubar.addMenu('&File')
file.addAction(exit)

def showDialog(self):
filename, _ = QFileDialog.getOpenFileName(self, 'Open file', './')
if filename:
file = open(filename)
data = file.read()
self.textEdit.setText(data)

if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
qb = OpenFile()
qb.show()
sys.exit(app.exec_())</span>

          我们在本示例程序中显示一个菜单栏,一个状态栏和一个被设置为中心部件的文本编辑器。其中状态栏的状态信息只有在用户想要打开文件时才会显示。单击菜单栏中的open选项将弹出文件对话框供用户选择文件。被选择的文件内容将被显示在文本编辑部件中。

         classOpenFile(QtWidgets.QMainWindow):

             ...

                self.textEdit =QTextEdit()

                self.setCentralWidget(self.textEdit)

         本示例程序是基于QMainWindow窗口部件的,因为我们需要将文本编辑器设置为中心部件(QWidget部件类没有提供setCentralWidget方法)。无须依赖布局管理器,QMainWindow即可轻松完成设置中心部件的工作(使用setCentralWidget方法)

         filename,  _ = QFileDialog.getOpenFileName(self, 'Openfile', './')

         该语句将弹出文件对话框。getOpenFileName()方法的第一个字符串参数'Openfile'将显示在弹出对话框的标题栏。第二个字符串参数用来指定对话框的工作目录。默认情况下文件过滤器被设置为不过滤任何文件(所有工作目录中的文件/文件夹都会被显示)。

         file= open(filename)

         data = file.read()

          self.textEdit.setText(data)

         以上三行语句将读取被选择的文件并将其内容显示在文本编辑器中。