Search code examples
qtqtextedit

QTextEdit Decrease Indentation of "tab" Key


I'm trying to make a little C++ text editor using Qt. When I press the "tab" key on my keyboard in the editor, it indents the line a lot more than necessary. I would like the code to indent by about 3 spaces rather than what looks to be 11 spaces. Is there any way to change the function of the tab key? Thanks.


Solution

  • To change TAB (ASCII character 9) width, you can use tabStopWidth property, which exists for both QTextEdit and QPlainTextEdit (doc link). It takes tab width in pixels. Note that TAB does not have a fixed width, instead it moves forward to next TAB stop, which are at pixel intervals determined by this property, starting from left edge.

    If you want TAB width to depend on font, you can use QFontMetrics class to get pixel width for some font and character. Example code:

        // this object is QTextEdit or QPlainTextEdit or a subclass
        int fontWidth = QFontMetrics(this->currentCharFormat().font()).averageCharWidth();
        this->setTabStopWidth( 3 * fontWidth );