QFileDialog继承了QDialog,具有父类的各种方法。
QFileDialog提供了一个对话框,允许用户选择文件或者目录,也允许用户遍历文件系统,用以选择一个或多个文件或者目录。
常用方法
# 获取一个打开文件的文件名
getOpenFileNames ([parent=None[, caption=””[, dir=””[, filter=””[, selectedFilter=””[, options=QFileDialog.Options()]]]]]])
# 获取保存的文件名
getSaveFileName ([parent=None[, caption=””[, dir=””[, filter=””[, selectedFilter=””[, options=QFileDialog.Options()]]]]]])
示例
ui文件
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QPushButton, QSizePolicy, QTextBrowser,
QWidget)
class Ui_Form(object):
def setupUi(self, Form):
if not Form.objectName():
Form.setObjectName(u"Form")
Form.resize(255, 274)
self.pushButton = QPushButton(Form)
self.pushButton.setObjectName(u"pushButton")
self.pushButton.setGeometry(QRect(20, 10, 80, 25))
self.pushButton_2 = QPushButton(Form)
self.pushButton_2.setObjectName(u"pushButton_2")
self.pushButton_2.setGeometry(QRect(130, 10, 80, 25))
self.textBrowser = QTextBrowser(Form)
self.textBrowser.setObjectName(u"textBrowser")
self.textBrowser.setGeometry(QRect(0, 40, 251, 231))
self.retranslateUi(Form)
QMetaObject.connectSlotsByName(Form)
# setupUi
def retranslateUi(self, Form):
Form.setWindowTitle(QCoreApplication.translate("Form", u"QFileDialog", None))
self.pushButton.setText(QCoreApplication.translate("Form", u"Open", None))
self.pushButton_2.setText(QCoreApplication.translate("Form", u"Save", None))
# retranslateUi
主文件
import sys
from PySide6 import QtCore,QtWidgets
from PySide6.QtWidgets import *
import pandas as pd
from ui_savetest import Ui_Form
class main(QWidget):
def __init__(self):
super().__init__()
self.ui = Ui_Form()
self.ui.setupUi(self)
self.__create_connections()
def __create_connections(self):
self.ui.pushButton.clicked.connect(self.openfile)
self.ui.pushButton_2.clicked.connect(self.savefile)
def openfile(self):
openname,_ = QFileDialog.getOpenFileName(self,"打开文件", '.','所有文件(*.*);;文本文件(*.txt);;Python文件(*.py)')
if openname:
with open(openname,'r') as f:
content = f.read()
self.ui.textBrowser.setText(content)
def savefile(self):
savename,_ = QFileDialog.getSaveFileName(self,"保存文件", '.','所有文件(*.*)')
txt1 = self.ui.textBrowser.toPlainText()
if savename:
with open(savename,'w') as f:
f.write(str(txt1))
if __name__ == '__main__':
app = QApplication(sys.argv)
m = main()
m.show()
sys.exit(app.exec())
```
标签:__,文件,Form,对话框,self,QFileDialog,import,pushButton
From: https://www.cnblogs.com/conpi/p/17141342.html