B4ST14
B4ST14

Reputation: 33

Auto add brackets or quotes in QTextEdit

I need to auto add brackets or quotes in my QTextEdit. Are there any function that do that or there is any documentations that explain that?

Upvotes: 1

Views: 240

Answers (1)

eyllanesc
eyllanesc

Reputation: 244003

You can override the keyPressEvent method and add the corresponding text if necessary while maintaining the cursor position.

import sys

from PyQt5 import QtCore, QtGui, QtWidgets


class TextEdit(QtWidgets.QTextEdit):
    def keyPressEvent(self, event):
        super().keyPressEvent(event)
        options = {"[": "]", "'": "'", '"': '"', "{": "}", "(": ")"}
        option = options.get(event.text())
        if option is not None:
            tc = self.textCursor()
            p = tc.position()
            self.insertPlainText(option)
            tc.setPosition(p)
            self.setTextCursor(tc)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = TextEdit()
    w.show()
    sys.exit(app.exec_())

Upvotes: 3

Related Questions