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

Insert text before and after selected text in PyQt5 QPlainTextEdit

我正在尝试在 QPlainTextEdit PyQt5 中的 selected 词之前和之后插入文本 例如: 当我写“我的名字是 AbdulWahab”和 select AbdulWahab 然后如果我按左括号然后 AbdulWahab 应该变成 (AbdulWahab)

谢谢

您可以使用多种不同的方法实现您想要的功能。
特别是捕捉 keyPressEvent 的部分。
我个人比较喜欢re-implementing 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_()