在PyQt5 QPlainTextEdit中的选定文本之前和之后插入文本



我正试图在QPlainTextEdit PyQt5中的所选单词前后插入Text例如:当我写";我的名字叫AbdulWahab;然后选择AbdulWahab,如果我按下左括号,那么AbdulWaab应该变成(AbdulWahap(

谢谢

您可以使用多种不同的方法来实现所需的功能
特别是捕捉按键PressEvent
我个人更喜欢重新实现QPlainTextEdit
你可以在代码中找到注释,我希望它能清楚地说明发生了什么。

这是您可以使用的示例代码:

import sys
from PyQt5 import QtGui
from PyQt5.QtCore import QEvent, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit

class SmartTextEdit(QPlainTextEdit):
def keyPressEvent(self, e: QtGui.QKeyEvent) -> None:
"""Catch every keypress and act on Left parentheses key"""
if e.type() == QEvent.KeyPress and e.key() == Qt.Key_ParenLeft:
cursor = self.textCursor()
if cursor.hasSelection():
# Here we confirmed to have some text selected, so wrap it in parentheses and replace selected text
cursor.insertText("(" + cursor.selectedText() + ")")
# Return here, we supress "(" being written to our text area
return
# not interesting key was pressed, pass Event to QPlainTextEdit
return super().keyPressEvent(e)

class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Create our SmartTextEdit
self.textarea = SmartTextEdit()
self.setCentralWidget(self.textarea)

if __name__ == "__main__":
app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()

最新更新