简体   繁体   中英

Qt: How to adjust the size of a QTextEdit object automatically

How can I automatically adjust the size of a QTextEdit object to automatically resize itself when the text string is larger than the given geometry?

In my example below, I define the geometry of the QTextEdit box to be 100x100. However, the text string that I would like to display could be much larger than that.

void MainWindow::display_text()
{
    QTextEdit *text = new QTextEdit(this);
    text->setWordWrapMode(QTextOption::NoWrap);
    text->setFontPointSize(24);

    /* Set the text box to be 100x100 */
    text->setGeometry(1, 1, 100, 100);

    /* The destination field may be too large to fit in the text box */
    QString arg = QString("Destination: %1").arg(destination);
    text->append(arg);

    text->show();
}

I would like the text string to be visible (ie no scrolling) and word-wrapping is turned off.

You can use QFontMetrics to calculate that.

QFontMetrics fm(text->font());
QString myText = text->toPlainText();
int calcWidth = fm.width(myText);
int calcHeight = fm.height(myText);

From that point you can use those values to set the geometry to whatever dimension you like.

text->setGeometry(1, 1, calcWidth, calcHeight);//Or whatever calculations you want

To change the size as you go, use signals and slots and just call that code again. QTextEdit has a nice textChanged signal you can use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM