python--pyQt5 文件 QFileDialog 获取文件路径保存文件选择文件夹 颜色(QColorDialog)、字体(QFontDialog)

原文: https://blog.csdn.net/jia666666/article/details/81560756

QFIleDialog是用于打开和保存文件的标准对话框。QFileDialog类继承自QDialog类
QFileDialog在打开文件时使用可文件过滤器,用于显示指定扩展名的文件,也可以设置使用QFileDialog打开文件时的起始目录和指定扩展名的文件

一、 QFileDialog类中的常用方法

方法 描述
getOpenFileName() 返回用户所选择文件的名称,并打开该文件
getSaveFileName() 使用用户选择的文件名保存文件
setFilter() 设置过滤器,只显示过滤器允许的文件类型

setFileMode() 可以选择的文件类型,枚举常量是:
QFileDialog.AnyFile:任何文件
QFileDialog.ExistingFile:已存在的文件
QFileDialog.Directory:文件目录
QFileDialog.ExistingFiles:已经存在的多个文件

二、 代码

2.1 打开文件,显示路径

filename = QFileDialog.getOpenFileName(self, "选取文件", " ", "Text files (*.txt)")
print(filename[0])
# print(type(filename[0]))  # str
self.report_UI.lineEdit_4.setText(filename[0])  # 将计算的结果生成在LineEdit里

2.2 写入内容

try:
	if filename:
	fb = open(filename[0], mode='w', encoding='utf-8')
	fb.write(data)  # 写入内容
	print('已保存')
except Exception as r:
	print("错误:", r)
	QMessageBox.warning(self, "警告", "请选择路径!", QtWidgets.QMessageBox.Yes)

python--pyQt5 文件 QFileDialog 获取文件路径保存文件选择文件夹 颜色(QColorDialog)、字体(QFontDialog)_第1张图片

三、例子

3.1 打开文件(QFileDialog)、颜色(QColorDialog)、字体(QFontDialog)对话框

from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QColorDialog,QFontDialog,QFileDialog,QGridLayout,QTextEdit)
import sys
from PyQt5.QtGui import QIcon


class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(500,500,400,300)
        self.setWindowTitle("标准输入对话框")
        self.setWindowIcon(QIcon("11.ico"))
        gridLayout = QGridLayout()
        self.txtFile = QTextEdit()
        self.fileContent = []
        gridLayout.addWidget(self.txtFile,0,0,3,1)
        self.btn1 = QPushButton("打开文件")
        self.btn2 = QPushButton("选择字体")
        self.btn3 = QPushButton("选择颜色")
        gridLayout.addWidget(self.btn1, 0, 1, 1, 1)
        gridLayout.addWidget(self.btn2, 1, 1, 1, 1)
        gridLayout.addWidget(self.btn3, 2, 1, 1, 1)
        self.setLayout(gridLayout)

        self.btn1.clicked.connect(self.openFile)
        self.btn2.clicked.connect(self.choseFont)
        self.btn3.clicked.connect(self.choseColor)

    def openFile(self):
        fname = QFileDialog.getOpenFileName(self,"打开文件",'./')
        if fname[0]:
            with open(fname[0],'r+',encoding='utf8',errors="ignore") as f:
                self.fileContent.append(f.read())
                txtCon = "".join(self.fileContent)
                self.txtFile.setText("\n"+txtCon)

    def choseFont(self):
        font , ok = QFontDialog.getFont()
        if ok:
            self.txtFile.setCurrentFont(font)
    def choseColor(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.txtFile.setTextColor(color)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

python--pyQt5 文件 QFileDialog 获取文件路径保存文件选择文件夹 颜色(QColorDialog)、字体(QFontDialog)_第2张图片

3.2 文件打印(QPageSetupDialog、QPrintDialog)

参考: https://zhuanlan.zhihu.com/p/29556459

from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QColorDialog,QFontDialog,QFileDialog,QGridLayout,QTextEdit,QDialog)
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtPrintSupport import QPageSetupDialog,QPrintDialog,QPrinter,QPrintPreviewDialog


class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()
        self.printer = QPrinter()

    def initUI(self):
        self.setGeometry(500,500,400,300)
        self.setWindowTitle("文件打印对话框")
        self.setWindowIcon(QIcon("11.ico"))
        gridLayout = QGridLayout()
        self.txtFile = QTextEdit()
        self.fileContent = []
        gridLayout.addWidget(self.txtFile,0,0,7,1)
        self.btn1 = QPushButton("打开文件")
        self.btn2 = QPushButton("打开多个文件")
        self.btn3 = QPushButton("选择字体")
        self.btn4 = QPushButton("选择颜色")
        self.btn5 = QPushButton("保存文件")
        self.btn6 = QPushButton("页面设置")
        self.btn7 = QPushButton("打印文件")
        gridLayout.addWidget(self.btn1, 0, 1, 1, 1)
        gridLayout.addWidget(self.btn2, 1, 1, 1, 1)
        gridLayout.addWidget(self.btn3, 2, 1, 1, 1)
        gridLayout.addWidget(self.btn4, 3, 1, 1, 1)
        gridLayout.addWidget(self.btn5, 4, 1, 1, 1)
        gridLayout.addWidget(self.btn6, 5, 1, 1, 1)
        gridLayout.addWidget(self.btn7, 6, 1, 1, 1)
        self.setLayout(gridLayout)

        self.btn1.clicked.connect(self.openFile)
        self.btn2.clicked.connect(self.openFiles)
        self.btn3.clicked.connect(self.choseFont)
        self.btn4.clicked.connect(self.choseColor)
        self.btn5.clicked.connect(self.saveFile)
        self.btn6.clicked.connect(self.pageSet)
        self.btn7.clicked.connect(self.printFile)

    def openFile(self):
        fname = QFileDialog.getOpenFileName(self,"打开文件",'./')
        if fname[0]:
            with open(fname[0],'r+',encoding='utf8',errors="ignore") as f:
                self.fileContent.append(f.read())
                txtCon = "".join(self.fileContent)
                self.txtFile.setText("\n"+txtCon)

    def openFiles(self):
        fnames = QFileDialog.getOpenFileNames(self,"打开多个文件",'./')
        print(fnames)
        if fnames[0]:
            for fname in fnames[0]:
                with open(fname,'r+',encoding='utf8',errors="ignore") as f:
                    self.fileContent.append(f.read()+"\n")
            txtsCon = "".join(self.fileContent)
            self.txtFile.setText(txtsCon)

    def choseFont(self):
        font , ok = QFontDialog.getFont()
        if ok:
            self.txtFile.setCurrentFont(font)

    def choseColor(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.txtFile.setTextColor(color)

    def saveFile(self):
        fileName = QFileDialog.getSaveFileName(self,"保存文件","./","Text files (*.txt)")
        if fileName[0]:
            with open(fileName[0],'w+',encoding='utf8') as f:
                f.write(self.txtFile.toPlainText())

    def pageSet(self):
        printSetDialog = QPageSetupDialog(self.printer,self)
        printSetDialog.exec_()

    def printFile(self):
        printDialog = QPrintDialog(self.printer,self)
        if QDialog.Accepted == printDialog.exec_():
            self.txtFile.print(self.printer)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

python--pyQt5 文件 QFileDialog 获取文件路径保存文件选择文件夹 颜色(QColorDialog)、字体(QFontDialog)_第3张图片

你可能感兴趣的:(pyside6,python,学习,python)