pyqt5-多行文本框的Ctrl+X快捷键

实现效果

pyqt5的QTextEdit按下Ctrl+X,如果当前有选中的文字,那么剪切这些内容,否则剪切当前行的内容

代码

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

你可能感兴趣的:(PyQt5,qt,python,开发语言)