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

实现效果

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

 代码

# 多行文本框
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()

猜你喜欢

转载自blog.csdn.net/m0_62653695/article/details/131962357
今日推荐