用pyqt5写一个ini文件编辑工具,右键提供查找功能
时间: 2023-05-11 13:04:56 浏览: 231
一款小巧的ini文件编辑器
4星 · 用户满意度95%
可以使用QSettings类来读写ini文件,使用QFileDialog类来选择文件,使用QLineEdit类来输入查找关键字,使用QTextEdit类来显示文件内容,使用QRegularExpression类来进行查找操作。以下是一个简单的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QLineEdit, QTextEdit, QAction
from PyQt5.QtCore import QSettings, QRegularExpression
class IniEditor(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Ini Editor')
self.setGeometry(100, 100, 800, 600)
self.textEdit = QTextEdit(self)
self.setCentralWidget(self.textEdit)
self.createActions()
self.createMenus()
def createActions(self):
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)
self.findAct = QAction('Find', self)
self.findAct.setShortcut('Ctrl+F')
self.findAct.triggered.connect(self.findText)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu('File')
self.fileMenu.addAction(self.openAct)
self.fileMenu.addAction(self.saveAct)
self.editMenu = self.menuBar().addMenu('Edit')
self.editMenu.addAction(self.findAct)
def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(self, 'Open File', '', 'Ini Files (*.ini)')
if fileName:
settings = QSettings(fileName, QSettings.IniFormat)
self.textEdit.setPlainText(settings.value(''))
def saveFile(self):
fileName, _ = QFileDialog.getSaveFileName(self, 'Save File', '', 'Ini Files (*.ini)')
if fileName:
settings = QSettings(fileName, QSettings.IniFormat)
settings.setValue('', self.textEdit.toPlainText())
def findText(self):
text, ok = QLineEdit.getText(self, 'Find', 'Enter keyword:')
if ok:
regex = QRegularExpression(text)
cursor = self.textEdit.textCursor()
cursor.movePosition(cursor.Start)
while True:
match = regex.match(cursor.block().text(), cursor.positionInBlock())
if match.hasMatch():
cursor.setPosition(match.capturedStart())
cursor.movePosition(cursor.Right, cursor.KeepAnchor, len(match.capturedText()))
self.textEdit.setTextCursor(cursor)
break
elif not cursor.movePosition(cursor.Down):
break
if __name__ == '__main__':
app = QApplication(sys.argv)
editor = IniEditor()
editor.show()
sys.exit(app.exec_())
```
这个工具可以打开、保存ini文件,还可以在文件中查找关键字。右键提供查找功能可以通过在菜单栏中添加一个Find菜单项来实现。
阅读全文