python-3.xpyqt5qplaintextedit

Insert text before and after selected text in PyQt5 QPlainTextEdit


I am trying to insertText before and after the selected word in QPlainTextEdit PyQt5 For example: when I write "My name is AbdulWahab" and select AbdulWahab then if I press left Parenthesis then AbdulWahab should turn into (AbdulWahab)

Thank you


Solution

  • You can achieve Your desired functionality using multiple different approaches.
    Especially part with catching keyPressEvent.
    I personally prefer re-implementing QPlainTextEdit.
    You can find comments in the code, I hope it's clear what's going on there.

    Here is sample code You can use:

    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_()