How to set number of lines for an QTextEdit?

2019-01-23 04:56发布

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?

5条回答
啃猪蹄的小仙女
2楼-- · 2019-01-23 05:13

This should work:

QTextEdit *myEdit = new QTextEdit(myContentString);
QSize myEditSize = myEdit->document()->size().toSize();
myEditSize.setWidth(QWIDGETSIZE_MAX);
myEdit->setMaximumSize(myEditSize);
查看更多
够拽才男人
3楼-- · 2019-01-23 05:16

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-23 05:19

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.

查看更多
劫难
5楼-- · 2019-01-23 05:26

Improving the accepted answer about QPlainTextEdit. In addition to lineSpacing, value for setFixedHeight should contain: 2 margins of the underlying QTextDocument, 2 widths of the frame and widget's contents margins. Besides that, QFontMetrics must be got from a font of the document, not of the widget itself. So, hypothetical function setHeight should read as follows:

void setHeight (QPlainTextEdit *ptxt, int nRows)
{
    QTextDocument *pdoc = ptxt->document ();
    QFontMetrics fm (pdoc->defaultFont ());
    QMargins margins = ptxt->contentsMargins ();
    int nHeight = fm.lineSpacing () * nRows +
        (pdoc->documentMargin () + ptxt->frameWidth ()) * 2 +
        margins.top () + margins.bottom ();
    ptxt->setFixedHeight (nHeight);
}
查看更多
Fickle 薄情
6楼-- · 2019-01-23 05:29

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.

查看更多
登录 后发表回答