pyqt5-自定义文本域1

快捷键支持:

CTRL+鼠标滚轮实现字体大小调整

支持复制当前行

剪切当前行

# 多行文本框
class TextEdit(QTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("background-color: #262626;color: #d0d0d0;")
        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()

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