Skip to content

CodeEditor

Qt Base Class: QPlainTextEdit

Signature: QPlainTextEdit(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None QPlainTextEdit(self, text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None

Base classes

Name Children Inherits
PlainTextEdit
prettyqt.widgets.plaintextedit

⋔ Inheritance diagram

graph TD
  1473367153600["custom_widgets.CodeEditor"]
  1473296323232["widgets.PlainTextEdit"]
  1473296321280["widgets.PlainTextEditMixin"]
  1473293679456["widgets.AbstractScrollAreaMixin"]
  1473293662864["widgets.FrameMixin"]
  1473293688240["widgets.WidgetMixin"]
  1473299815024["core.ObjectMixin"]
  140713234304496["builtins.object"]
  1473245548480["gui.PaintDeviceMixin"]
  1473290657408["QtWidgets.QPlainTextEdit"]
  1473290616416["QtWidgets.QAbstractScrollArea"]
  1473290626176["QtWidgets.QFrame"]
  1473290849680["QtWidgets.QWidget"]
  1473288842240["QtCore.QObject"]
  1473291690208["Shiboken.Object"]
  1473300082368["QtGui.QPaintDevice"]
  1473296323232 --> 1473367153600
  1473296321280 --> 1473296323232
  1473293679456 --> 1473296321280
  1473293662864 --> 1473293679456
  1473293688240 --> 1473293662864
  1473299815024 --> 1473293688240
  140713234304496 --> 1473299815024
  1473245548480 --> 1473293688240
  140713234304496 --> 1473245548480
  1473290657408 --> 1473296323232
  1473290616416 --> 1473290657408
  1473290626176 --> 1473290616416
  1473290849680 --> 1473290626176
  1473288842240 --> 1473290849680
  1473291690208 --> 1473288842240
  140713234304496 --> 1473291690208
  1473300082368 --> 1473290849680
  1473291690208 --> 1473300082368

🛈 DocStrings

Bases: PlainTextEdit

Super basic code editor.

Source code in prettyqt\custom_widgets\codeeditor.py
class CodeEditor(widgets.PlainTextEdit):
    """Super basic code editor."""

    def __init__(self, language: str = "python", **kwargs):
        super().__init__(**kwargs)
        self.line_area = LineNumberArea(self)
        self.blockCountChanged.connect(self.update_line_area_width)
        self.updateRequest.connect(self.update_line_area)
        self.set_font(gui.Font.mono(as_qt=True))
        self.update_line_area_width(0)
        self.set_current_line_color(gui.Color(128, 128, 128, 20))
        self.set_syntaxhighlighter(language)

    #     self.delimiter = "    "
    #     self.completion_state = 0
    #     self.completing = False
    #     self.cursorPositionChanged.connect(self.reset_completion)

    # def keyPressEvent(self, event):
    #     match event.key():
    #         case constants.Key.Key_Backtab if self.textCursor().hasSelection():
    #             start_cursor = self.get_textCursor()
    #             with start_cursor.edit_block():
    #                 start_pos = start_cursor.selectionStart()
    #                 start_cursor.setPosition(start_pos)
    #                 start_cursor.move_position("start_of_line")
    #                 start_cursor.clearSelection()
    #                 end_cursor = self.get_text_cursor()
    #                 end_pos = end_cursor.selectionEnd()
    #                 end_cursor.setPosition(end_pos)
    #                 end_cursor.move_position("start_of_line")
    #                 delimit_len = len(self.delimiter)
    #                 while start_cursor.anchor() != end_cursor.position():
    #                     start_cursor.move_position(
    #                         "next_character", mode="keep", n=delimit_len
    #                     )
    #                     if start_cursor.selectedText() == self.delimiter:
    #                         start_cursor.removeSelectedText()
    #                     start_cursor.move_position("next_block")
    #                 start_cursor.move_position(
    #                     "next_character", mode="keep", n=delimit_len
    #                 )
    #                 if start_cursor.selectedText() == self.delimiter:
    #                     start_cursor.removeSelectedText()
    #         case constants.Key.Key_Tab if self.textCursor().hasSelection():
    #             start_cursor = self.get_text_cursor()
    #             with start_cursor.edit_block():
    #                 start_pos = start_cursor.selectionStart()
    #                 start_cursor.setPosition(start_pos)
    #                 start_cursor.move_position("start_of_line")
    #                 end_cursor = self.get_text_cursor()
    #                 end_pos = end_cursor.selectionEnd()
    #                 end_cursor.setPosition(end_pos)
    #                 end_cursor.move_position("start_of_line")
    #                 while start_cursor.position() != end_cursor.position():
    #                     start_cursor.insertText(self.delimiter)
    #                     start_cursor.move_position("next_block")
    #                 start_cursor.insertText(self.delimiter)
    #         case constants.Key.Key_Escape if self.completion_state > 0:
    #             self.completion_state = 0
    #             cursor = self.get_text_cursor()
    #             with cursor.edit_block():
    #                 self.selecter.replace_block_at_cursor(self._orig_text)
    #             self._orig_text == None
    #         case constants.Key.Key_Tab:
    #             if self.is_start():
    #                 self.textCursor().insertText(self.delimiter)
    #             else:
    #                 cursor = self.get_text_cursor()
    #                 with cursor.edit_block():
    #                     self.completing = True
    #                     if self.completion_state == 0:
    #                         self._orig_text = self.textCursor().block().text()
    #                     if self.completion_state > 0:
    #                         self.selecter.replace_block_at_cursor(self._orig_text)
    #                     new_text = self.completer.complete(
    #                         self._orig_text, self.completion_state
    #                     )
    #                     if new_text:
    #                         if new_text.find("(") > 0:
    #                             new_text = new_text[0 : new_text.find("(") + 1]
    #                         self.completion_state += 1
    #                         self.selecter.replace_block_at_cursor(new_text)
    #                     else:
    #                         self.completion_state = 0
    #                         self.selecter.replace_block_at_cursor(self._orig_text)
    #                         self._orig_text == None
    #                 self.completing = False
    #         case _:
    #             return super().keyPressEvent(event)

    # def reset_completion(self):
    #     if not self.completing:
    #         self.completion_state = 0

    # def is_start(self) -> bool:
    #     temp_cursor = self.textCursor()
    #     if temp_cursor.positionInBlock() == 0:
    #         return True
    #     start_text = temp_cursor.block().text()[0 : temp_cursor.positionInBlock()]
    #     delim = set(self.delimiter)
    #     return set(start_text) - delim == set()

    def resizeEvent(self, event):
        super().resizeEvent(event)

        cr = self.contentsRect()
        rect = core.Rect(cr.left(), cr.top(), self.line_area_width(), cr.height())
        self.line_area.setGeometry(rect)

    def line_area_width(self) -> int:
        digits = len(str(self.blockCount()))
        return 3 + self.fontMetrics().boundingRect("9").width() * digits

    def update_line_area_width(self, _):
        self.setViewportMargins(self.line_area_width(), 0, 0, 0)

    def update_line_area(self, rect: core.QRect, dy: int):
        if dy:
            self.line_area.scroll(0, dy)
        else:
            self.line_area.update(0, rect.y(), self.line_area.width(), rect.height())

        if rect.contains(self.viewport().rect()):
            self.update_line_area_width(0)

    def line_area_paintevent(self, event):
        with gui.Painter(self.line_area) as painter:
            painter.fill_rect(event.rect(), "lightgray")

            block = self.firstVisibleBlock()
            block_number = block.blockNumber()
            top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
            bottom = top + self.blockBoundingRect(block).height()
            width = self.line_area.width()
            height = self.fontMetrics().height()
            painter.set_color("black")
            while block.isValid() and (top <= event.rect().bottom()):
                if block.isVisible() and (bottom >= event.rect().top()):
                    number = str(block_number + 1)
                    painter.drawText(
                        0, int(top), width, height, constants.ALIGN_RIGHT, number
                    )
                block = block.next()
                top = bottom
                bottom = top + self.blockBoundingRect(block).height()
                block_number += 1

⌗ Property table

Qt Property Type Doc
objectName QString
modal bool
windowModality Qt::WindowModality
enabled bool
geometry QRect
frameGeometry QRect
normalGeometry QRect
x int
y int
pos QPoint
frameSize QSize
size QSize
width int
height int
rect QRect
childrenRect QRect
childrenRegion QRegion
sizePolicy QSizePolicy
minimumSize QSize
maximumSize QSize
minimumWidth int
minimumHeight int
maximumWidth int
maximumHeight int
sizeIncrement QSize
baseSize QSize
palette QPalette
font QFont
cursor QCursor
mouseTracking bool
tabletTracking bool
isActiveWindow bool
focusPolicy Qt::FocusPolicy
focus bool
contextMenuPolicy Qt::ContextMenuPolicy
updatesEnabled bool
visible bool
minimized bool
maximized bool
fullScreen bool
sizeHint QSize
minimumSizeHint QSize
acceptDrops bool
windowTitle QString
windowIcon QIcon
windowIconText QString
windowOpacity double
windowModified bool
toolTip QString
toolTipDuration int
statusTip QString
whatsThis QString
accessibleName QString
accessibleDescription QString
layoutDirection Qt::LayoutDirection
autoFillBackground bool
styleSheet QString
locale QLocale
windowFilePath QString
inputMethodHints QFlags
frameShape QFrame::Shape
frameShadow QFrame::Shadow
lineWidth int
midLineWidth int
frameWidth int
frameRect QRect
verticalScrollBarPolicy Qt::ScrollBarPolicy
horizontalScrollBarPolicy Qt::ScrollBarPolicy
sizeAdjustPolicy QAbstractScrollArea::SizeAdjustPolicy
tabChangesFocus bool
documentTitle QString
undoRedoEnabled bool
lineWrapMode QPlainTextEdit::LineWrapMode
readOnly bool
plainText QString
overwriteMode bool
tabStopDistance double
cursorWidth int
textInteractionFlags QFlags
blockCount int
maximumBlockCount int
backgroundVisible bool
centerOnScroll bool
placeholderText QString
current_line_color QColor Color to use for current line highlighting
validation_color QColor Color to use for invalid text