How to set number of lines for an QTextEdit?

22,041

Solution 1

If you use QPlainTextEdit, something like this should do the trick:

void SetHeight (QPlainTextEdit* edit, int nRows)
  {
  QFontMetrics m (edit -> font()) ;
  int RowHeight = m.lineSpacing() ;
  edit -> setFixedHeight  (nRows * RowHeight) ;
  }

You might want to add two or three pixels as margin; experiment will tell.

Solution 2

Use QFont to determine the height of a single line of text in the QTextEdit (QTextEdit should have a font property). After that multiply the QFont's height value with the number of lines you want to show and set the widget's (minimum-)height to that value.

Solution 3

This should work:

QTextEdit *myEdit = new QTextEdit(myContentString);
QSize myEditSize = myEdit->document()->size().toSize();
myEditSize.setWidth(QWIDGETSIZE_MAX);
myEdit->setMaximumSize(myEditSize);

Solution 4

QTextEdit is a normal widget, so you can use minimumHeight property. I believe, however, that it is really impossible to set minimum height based on number of lines. This would resize automagically the minimum size of a widget every time you change size of the font. But if you know the size of the font, you can set some usable minimum size of your widget.

Share:
22,041
Mnementh
Author by

Mnementh

My name is Jörgen Kosche. I'm a programmer using mostly Java.

Updated on October 29, 2020

Comments

  • Mnementh
    Mnementh over 3 years

    I use a QTextEdit for some inputs. But I want to adjust the height of the box. Can I set the height based on the number of lines I want to have visible at a time?

  • TonyK
    TonyK over 13 years
    The trouble with QTextEdit is that each line can have a different height. If you only need a single text format (but with different colours allowed), maybe QPlainTextEdit is better.
  • TonyK
    TonyK over 13 years
    QTextEdit has mouse wheel zoom enabled by default, so you would need to turn this off.
  • Goswin von Brederlow
    Goswin von Brederlow about 9 years
    This ignores the margin and border of the widget so the last line is cut of. The amount of pixels to add depends on the theme in use so it's more complex than this.