假设你是一名程序员,写一段代码,用pyqt打开本地记事本文件
时间: 2024-03-05 07:48:41 浏览: 18
好的,以下是用 PyQt 打开本地记事本文件的代码示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
class Notepad(QMainWindow):
def __init__(self):
super().__init__()
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
openFile = QAction('Open', self)
openFile.setShortcut('Ctrl+O')
openFile.triggered.connect(self.showDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Notepad')
self.show()
def showDialog(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
if fname[0]:
with open(fname[0], 'r') as f:
data = f.read()
self.textEdit.setText(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Notepad()
sys.exit(app.exec_())
```
这里我们定义了一个 Notepad 类,用来继承 QMainWindow 类,并添加了一个 QTextEdit 作为中心窗口部件,以及一个打开文件的 QAction。在打开文件的时候,我们使用 QFileDialog 打开一个文件选择对话框,并读取所选文件的内容,将其显示在 QTextEdit 中。最后,我们创建了一个 QApplication 实例,并将 Notepad 实例传给它,最终运行整个应用。