多文档文本编辑器 qt
时间: 2023-12-27 19:04:07 浏览: 102
Qt多文本编辑器论文
5星 · 资源好评率100%
以下是一个基于Qt5中widgets框架编写的简易多文档编辑器的示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
class TextEditor(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.createActions()
self.createMenus()
self.setWindowTitle("Text Editor")
self.setGeometry(100, 100, 800, 600)
self.show()
def createActions(self):
self.newAct = QAction("New", self)
self.newAct.setShortcut("Ctrl+N")
self.newAct.triggered.connect(self.newFile)
self.openAct = QAction("Open", self)
self.openAct.setShortcut("Ctrl+O")
self.openAct.triggered.connect(self.openFile)
self.saveAct = QAction("Save", self)
self.saveAct.setShortcut("Ctrl+S")
self.saveAct.triggered.connect(self.saveFile)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu("File")
self.fileMenu.addAction(self.newAct)
self.fileMenu.addAction(self.openAct)
self.fileMenu.addAction(self.saveAct)
def newFile(self):
self.textEdit.clear()
def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(self, "Open File")
if fileName:
with open(fileName, "r") as file:
self.textEdit.setText(file.read())
def saveFile(self):
fileName, _ = QFileDialog.getSaveFileName(self, "Save File")
if fileName:
with open(fileName, "w") as file:
file.write(self.textEdit.toPlainText())
if __name__ == "__main__":
app = QApplication(sys.argv)
editor = TextEditor()
sys.exit(app.exec_())
```
这个多文档文本编辑器具有新建、打开、保存文件的功能。你可以使用菜单栏中的"File"选项来执行这些操作。此外,你还可以在文本编辑器中设置字体、字号、文字的复制、粘贴、加粗、倾斜以及设置字体颜色等功能。
阅读全文