七月 25

Pyside2教程:记事本小程序

import sys
from PySide2 import QtWidgets as qtw
from PySide2 import QtGui as qtg
from PySide2 import QtCore as qtc

# 设置对话框
class SettingsDialog(qtw.QDialog):
    """Dialog for setting the settings"""
    def __init__(self, settings, parent=None):
        super().__init__(parent, modal=True)
        self.setLayout(qtw.QFormLayout())
        self.settings = settings
        self.layout().addRow(qtw.QLabel('<h1>设置</h1>'))
        self.show_warning_cb = qtw.QCheckBox(checked=settings.get('show_warnings'))
        self.layout().addRow('显示警告', self.show_warning_cb)
        self.accept_btn = qtw.QPushButton('Ok', clicked=self.accept)
        self.cancel_btn = qtw.QPushButton('Cancel', clicked=self.reject)
        self.layout().addRow(self.accept_btn, self.cancel_btn)

    def accept(self):
        self.settings['show_warnings'] = self.show_warning_cb.isChecked()
        super().accept()

# 将主程序封装成类
class MainWindow(qtw.QMainWindow):

    # 传入的两个参数分别为公司名和程序名
    settings = {'show_warnings': False}

    def __init__(self):
        # 引入父类的__init__方法
        super().__init__(parent=None)
        # Main UI code goes here
        # 设置centralWidget
        self.textedit = qtw.QTextEdit()
        self.setCentralWidget(self.textedit)

        # 设置statusBar。但是这些代码可以省略,因为QMainWindow的statusBar()方法会自动创建一个状态栏
        # status_bar = qtw.QStatusBar()
        # self.setStatusBar(status_bar)
        # status_bar.showMessage('欢迎来到安静编辑器')
        self.statusBar().showMessage('欢迎来到安静编辑器')
        charcount_label = qtw.QLabel('字符:0')
        self.textedit.textChanged.connect(lambda: charcount_label.setText("字符:"+str(len(self.textedit.toPlainText()))))
        self.statusBar().addPermanentWidget(charcount_label)

        # 设置菜单栏
        menubar = self.menuBar()
        file_menu = menubar.addMenu('文件')
        edit_menu = menubar.addMenu('编辑')
        help_menu = menubar.addMenu('帮助')

        # 给菜单栏添加内容。第一个参数为名字,第二个参数为执行的操作。返回一个QAction
        open_action = file_menu.addAction('打开')
        save_action = file_menu.addAction('保存')
        quit_action = file_menu.addAction('退出', self.destroy)
        edit_menu.addAction('撤销', self.textedit.undo)

        # 更复杂的操作可以自己创建一个QAction,然后添加到某个菜单中
        redo_action = qtw.QAction('重做', self)
        redo_action.triggered.connect(self.textedit.redo)
        edit_menu.addAction(redo_action)
        edit_menu.addAction('字体', self.set_font)

        help_menu.addAction('设置', self.show_settings)

        # 设置工具栏
        toolbar = self.addToolBar('文件')
        # 设置工具栏可以放置的位置
        toolbar.setAllowedAreas(qtc.Qt.TopToolBarArea | qtc.Qt.BottomToolBarArea)
        toolbar.addAction(open_action)
        toolbar.addAction(save_action)

        # 获取系统自带的图标
        open_icon = self.style().standardIcon(qtw.QStyle.SP_DirOpenIcon)
        save_icon = self.style().standardIcon(qtw.QStyle.SP_DriveHDIcon)

        # 设置图标
        open_action.setIcon(open_icon)
        save_action.setIcon(save_icon)

        open_action.triggered.connect(self.openFile)
        save_action.triggered.connect(self.saveFile)

        # 设置dock
        dock = qtw.QDockWidget('替换')
        self.addDockWidget(qtc.Qt.LeftDockWidgetArea, dock)

        dock.setFeatures(qtw.QDockWidget.DockWidgetMovable | qtw.QDockWidget.DockWidgetFloatable)

        # 创建dock中的界面
        replace_widget = qtw.QWidget()
        replace_widget.setLayout(qtw.QVBoxLayout())
        dock.setWidget(replace_widget)

        self.search_text_inp = qtw.QLineEdit(placeholderText='搜索')
        self.replace_text_inp = qtw.QLineEdit(placeholderText='替换')
        search_and_replace_btn = qtw.QPushButton('搜索和替换', clicked=self.search_and_replace)
        replace_widget.layout().addWidget(self.search_text_inp)
        replace_widget.layout().addWidget(self.replace_text_inp)
        replace_widget.layout().addWidget(search_and_replace_btn)
        replace_widget.layout().addStretch()

        help_menu.addAction('关于', self.showAboutDialog)

        # response = qtw.QMessageBox.question(self, 'Beta版本提醒', '目前软件仍在测试阶段,请问您确定要使用吗?')
        splash_screen = qtw.QMessageBox()
        splash_screen.setWindowTitle('安静编辑器')
        splash_screen.setText('内测版本警告')
        splash_screen.setInformativeText('这是非常早期的版本,你确定要使用吗')
        splash_screen.setDetailedText('本软件仅供内部使用,很多功能都是针对特定的软件而设置')
        splash_screen.setWindowModality(qtc.Qt.WindowModal)
        splash_screen.addButton(qtw.QMessageBox.Yes)
        splash_screen.addButton(qtw.QMessageBox.No)
        response = splash_screen.exec()

        if response == qtw.QMessageBox.No:
            self.close()
            sys.exit()

        # End main UI code
        # 显示主窗口
        self.show()

    def search_and_replace(self):
        s_text = self.search_text_inp.text()
        r_text = self.replace_text_inp.text()

        if s_text:
            self.textedit.setText(self.textedit.toPlainText().replace(s_text, r_text))

    def showAboutDialog(self):
        qtw.QMessageBox.about(self, '关于文本编辑器', '这是在Pyside2环境下编写的文字编辑器')

    def openFile(self):
        filename, _ = qtw.QFileDialog.getOpenFileName(
            self,
            '请选择要打开的文件',
            qtc.QDir.homePath(),
            'Text Files (*.txt) ;;Python Files (*.py) ;;All Files (*)',
            'Python Files (*.py)',
            qtw.QFileDialog.DontResolveSymlinks
        )
        if filename:
            with open(filename, 'r', encoding='utf-8') as fh:
                self.textedit.setText(fh.read())

    def saveFile(self):
        filename, _ = qtw.QFileDialog.getSaveFileName(
            self,
            "Select the file to save to…",
            qtc.QDir.homePath(),
            'Text Files (*.txt) ;;Python Files (*.py) ;;All Files (*)'
        )
        if filename:
            with open(filename, 'w', encoding='utf-8') as fh:
                fh.write(self.textedit.toPlainText())

    def set_font(self):
        current = self.textedit.currentFont()
        accepted, font = qtw.QFontDialog.getFont(current, self)
        if accepted:
            self.textedit.setCurrentFont(font)

    def show_settings(self):
        settings_dialog = SettingsDialog(self.settings, self)
        settings_dialog.exec_()

if __name__ == '__main__':
    app = qtw.QApplication()
    main_window = MainWindow()
    sys.exit(app.exec_())


文章由安静原创,发表于www.ajnote.com。转载请注明出处

发表 2020年7月25日 自 anjing 类别 "Pyside2学习笔记

发表评论

电子邮件地址不会被公开。 必填项已用*标注