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

Realize the effect

QTextEdit of pyqt5 press Ctrl+C. If there is currently selected text, copy the content, otherwise copy the content of the current line.

 code

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

    # Ctrl+鼠标滚轮调整字体大小
    def wheelEvent(self, event):
        # 捕捉鼠标滚轮事件
        modifiers = QApplication.keyboardModifiers()

        if modifiers == Qt.ControlModifier:
            # 如果按下了 Ctrl 键
            delta = event.angleDelta().y()
            font = self.font()

            # 根据滚轮方向调整字体大小
            if delta > 0:
                font.setPointSize(font.pointSize() + 1)
            else:
                font.setPointSize(font.pointSize() - 1)

            self.setFont(font)
        else:
            # 如果没有按下 Ctrl 键,则使用默认滚轮事件处理
            super().wheelEvent(event)

    # Ctrl+X,Ctrl+C
    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()
        elif event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_C:
            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.copy_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()

    # 复制当前行内容
    def copy_current_line(self):
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine)
        cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
        self.setTextCursor(cursor)
        self.copy()

Guess you like

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