How to change the width of tabs in a QPlainTextEdit
Asked Answered
T

1

10

When using the QPlaintextEdit in PyQt5, if I press the Tab button on my keyboard I get a tab space which is equal to size of six spaces together. But I want it to be the size of four spaces, so that when I use:

TextEdit.setPlainTextEdit('\t')

I should get a indentation of a tab space, which is as long as four spaces altogether.

I tried using four spaces instead of a tab space, but things got complex, as code became more lengthy.

Tachygraphy answered 5/5, 2018 at 15:6 Comment(0)
E
14

The width of a tab can be set with setTabStopDistance. This takes a floating-point value, which can be calculated by using the QFontMetricsF class:

textedit = QtWidgets.QPlainTextEdit()
textedit.setTabStopDistance(
    QtGui.QFontMetricsF(textedit.font()).horizontalAdvance(' ') * 4)

However, this method was only introduced in Qt-5.10, so for Qt4 and older versions of Qt5, you must use setTabStopWidth (which is now documented as obsolete):

textedit = QtWidgets.QPlainTextEdit()
textedit.setTabStopWidth(textedit.fontMetrics().width(' ') * 4)

The big disadvantage of this method is that it only takes integer values. This means that it isn't guaranteed give accurate results with fonts that have non-integer character widths (e.g. the DejaVu fonts and many others).

Excavate answered 5/5, 2018 at 18:41 Comment(1)
These days QFontMetrics::width() is deprecated (since Qt-5.11 I believe). It's recommended to use QFontMetricsF::horizontalAdvance() instead from now on.Royall

© 2022 - 2024 — McMap. All rights reserved.