Search code examples
python-3.xpyqt5

Implementing auto-indentation for python in QPlainTextEdit (PyQt5)


I'm looking to implement something like this:

enter image description here

But I have no idea where to start, right now my text editor has syntax highlighting and linenumbers so the next step would be to add auto-indetation. How would I go about adding it? Are there any examples? The main part of my code right now can be found here:

https://github.com/Fuchsiaff/pypad/blob/master/src/main.py


Solution

  • This will need a lot of refinement, but should give you an idea. You basically just want to check what the last line ends with to determine if you need an indent, then insert it in the text edit.

        self.text_edit = QtWidgets.QTextEdit()
        self.text_edit.textChanged.connect(self.add_indent)
    
    def add_indent(self):
        if self.text_edit.toPlainText().endswith(':\n'):
            self.text_edit.insertPlainText('    ')