凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

21. PyQt6 QFileDialog

2023-10-17 python 196
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QFileDialog
from PyQt6.QtGui import QGuiApplication, QIcon, QAction
from pathlib import Path


class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.text_edit = None
        self.initUI()

    def initUI(self):
        self.setWindowTitle("PyQt6 QFileDialog")

        self.text_edit = QTextEdit()
        self.setCentralWidget(self.text_edit)

        open_btn = QAction(QIcon("file-open.png"), "打开", self)
        open_btn.setShortcut("Ctrl+O")
        open_btn.setStatusTip("打开新文件")
        open_btn.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        file_menu = menubar.addMenu("&文件")
        file_menu.addAction(open_btn)

        self.setGeometry(100, 100, 400, 300)
        self.center()

    def showDialog(self):
        home_dir = str(Path.home())
        fname = QFileDialog.getOpenFileName(self, "打开文件", home_dir)
        if fname[0]:
            f = open(fname[0], "r", encoding="utf-8")

            with f:
                data = f.read()
                self.text_edit.setText(data)

    def center(self):
        qr = self.frameGeometry()
        cp = QGuiApplication.primaryScreen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    cls_app = App()
    cls_app.show()
    sys.exit(app.exec())

image.png

文章评论

0条评论