Archie Gertsman
Archie Gertsman

Reputation: 1661

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.

Upvotes: 3

Views: 2021

Answers (1)

hyde
hyde

Reputation: 62906

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 );

Upvotes: 6

Related Questions