pyqt5-Ctrl+X shortcut key for multi-line text box

Realize the effect

QTextEdit of pyqt5 presses Ctrl+X. If there is currently selected text, then cut the content, otherwise cut the content of the current line.

code

class TextEdit(QTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFont(standard_font)  # 设置标准字体

    # Ctrl+X
    def keyPressEvent(self, event):
        if event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_X:
            if self.textCursor().hasSelection():
                # If there is selected text, cut the selection
                super().keyPressEvent(event)
            else:
                # If no text is selected, cut the entire line
                self.cut_current_line()
        else:
            super().keyPressEvent(event)

    def cut_current_line(self):
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine)
        cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
        self.setTextCursor(cursor)
        self.cut()

Guess you like

Origin blog.csdn.net/m0_62653695/article/details/131962124