pyqt_0">pyqt小案例实现简易文本编辑器
分析
实现了一个简单的文本编辑器,使用PyQt5框架构建。以下是代码的主要功能和特点:
主窗口类 (MyWindow):
- 继承自 QWidget 类。
- 使用 .ui 文件加载用户界面布局。
- 设置窗口标题、状态栏消息等。
- 创建菜单栏及其子菜单项(文件和编辑),并绑定相应的槽函数。
菜单操作:
- 新建文件:清空文本编辑区域。
- 打开文件:通过文件对话框选择文件后读取其内容并显示在文本编辑区域。
- 保存文件:通过文件对话框选择保存位置并将文本编辑区域的内容写入文件。
- 退出程序:关闭窗口前询问是否保存当前文件。
语法高亮 (SyntaxHighlighter):
- 继承自 QSyntaxHighlighter 类。
- 定义关键字、注释和字符串的格式规则。
- 实现 highlightBlock 方法以根据定义的规则对每一行文本进行高亮处理。
运行程序:
- 创建 QApplication 实例。
- 初始化 MyWindow 窗口实例并展示。
- 进入应用程序的事件循环。
主要组件
- uic: 用于从 .ui 文件加载 Qt 用户界面。
- QFileDialog: 提供打开和保存文件的对话框。
- QMessageBox: 显示消息对话框以获取用户反馈。
- QSyntaxHighlighter: 用于实现文本编辑区的语法高亮功能。
代码
from PyQt5 import uic
import sys
import re
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QMessageBox
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QColor, QFont
from PyQt5.QtCore import QRegularExpressionclass MyWindow(QWidget):def __init__(self):super().__init__()self.init_ui()def init_ui(self):self.ui = uic.loadUi("./文本编辑器.ui")print(self.ui.__dict__) self.ui.setWindowTitle("文本编辑器") # 修改标题的名称self.textEdit = self.ui.textEditself.syntaxHighlighter = SyntaxHighlighter(self.textEdit.document())self.statusBar = self.ui.statusBarself.statusBar().showMessage('状态栏')# 加载好ui文件之后再进行设置菜单栏menu = self.ui.menubarfile_menu = menu.addMenu("文件")# 清空文本self.create_file = file_menu.addAction("新建")self.create_file.setShortcut('Ctrl+N')self.create_file.triggered.connect(self.newFile)# 打开文件动作self.open = file_menu.addAction("打开")self.open.setShortcut("Ctrl+O")self.open.triggered.connect(self.openFile)self.save = file_menu.addAction("保存")self.save.setShortcut("Ctrl+S")self.save.triggered.connect(self.saveFile)self.exit = file_menu.addAction("退出")self.exit.setShortcut("Ctrl+E")self.exit.triggered.connect(self.closeEvent)edit_menu = menu.addMenu("编辑")edit_menu.addAction("复制")edit_menu.addAction("粘贴")edit_menu.addAction("剪切")def newFile(self):# 清空文本编辑区域self.textEdit.clear()self.statusBar().showMessage('新文件')def openFile(self):# 打开文件对话框,读取文件内容,将其显示在textEdit中fileName, _ = QFileDialog.getOpenFileName(self, '打开文件', '', '文本文件 (*.txt);;所有文件 (*)')if fileName:with open(fileName, 'r', encoding='utf-8') as file:self.textEdit.setText(file.read())self.statusBar().showMessage('打开新文件')def saveFile(self):# 保存文件对话框,打开一个文件,将textEdit中的内容写进去fileName, _ = QFileDialog.getSaveFileName(self, '保存文件', '', '文本文件 (*.txt);;所有文件 (*)')if fileName:with open(fileName, 'w', encoding='utf-8') as file:file.write(self.textEdit.toPlainText())def closeEvent(self, event):# 关闭窗口时提示保存reply = QMessageBox.question(self, '退出', '你是否想保存文件?',QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)if reply == QMessageBox.Yes:self.saveFile()event.accept()elif reply == QMessageBox.No:event.accept()else:event.ignore()class SyntaxHighlighter(QSyntaxHighlighter):def __init__(self, parent=None):super().__init__(parent)keywordFormat = QTextCharFormat()keywordFormat.setForeground(QColor("blue"))keywordFormat.setFontWeight(QFont.Bold)commentFormat = QTextCharFormat()commentFormat.setForeground(QColor("green"))commentFormat.setFontItalic(True)stringFormat = QTextCharFormat()stringFormat.setForeground(QColor("red"))stringFormat.setFontWeight(QFont.Bold)keywords = ["def", "class", "import", "from", "if", "else", "elif", "for", "while", "return", "try", "except"]self.highlightingRules = []for word in keywords:escaped_word = re.escape(word)rule = QRegularExpression(rf"\b{escaped_word}\b")self.highlightingRules.append((rule, keywordFormat))rule = QRegularExpression(r"#[^\n]*")self.highlightingRules.append((rule, commentFormat))rule = QRegularExpression(r'"([^"\\]|\\.)*"')self.highlightingRules.append((rule, stringFormat))def highlightBlock(self, text):for pattern, format in self.highlightingRules:matchIterator = pattern.globalMatch(text)while matchIterator.hasNext():match = matchIterator.next()self.setFormat(match.capturedStart(), match.capturedLength(), format)if __name__=="__main__":app = QApplication(sys.argv)w = MyWindow()# 展示窗口w.ui.show()app.exec()