【问题标题】:Resizing QT's QTextEdit to Match Text Width调整 QT 的 QTextEdit 大小以匹配文本宽度
【发布时间】:2014-01-30 20:11:52
【问题描述】:

我有一个 QMainWindow,它有一个 QVBoxLayout,里面有一个 QTextEdit。我对后者使用 insertHtml 和一个固定的 CSS,它基本上归结为具有恒定宽度的等宽行,所以它应该是可预测的,一旦输入一行,QTextEdit 应该有多宽才能显示整个文本。问题是,我不知道如何获得那个宽度。我尝试了很多东西:adjustSize(),获取底层 QTextDocument 的大小,QFontMetrics(不测量具有由样式表修改的类的 HTML),甚至做

QFont f("monospace");
QFontMetrics fm(f);
QString s = QString("A").repeated(MyTextWidth);
unsigned NewWidth = fm.width(s)

产生一个值,该值应用于带有 setFixedWidth 的 QTextEdit 会给出不正确的结果。 那么如何在不使用水平滚动条的情况下自动设置 QTextEdit 的宽度(以及拥有它的 QMainWindow)以显示整行文本?

【问题讨论】:

    标签: html css qt qtextedit


    【解决方案1】:

    您可以使用QTextDocument::idealWidth 确定实际文本宽度。在查询理想宽度之前,让QTextEdit 可见很重要。不要忘记为其值添加内容边距。

    QTextEdit textEdit;
    textEdit.setHtml("<p>test test test test test test</p><p>|||||||||</p>");
    textEdit.show();
    textEdit.setFixedWidth(textEdit.document()->idealWidth() +
                           textEdit.contentsMargins().left() +
                           textEdit.contentsMargins().right());
    

    结果:

    【讨论】:

    • 听起来确实不错,但它在这方面不起作用,它包装了您的示例文本。请记住,这是我第一次使用 Qt。我的完整代码是:class Test : public QMainWindow { public: Test(QWidget *parent = 0) : QMainWindow(parent) { QTextEdit *text = new QTextEdit(); text-&gt;setReadOnly(true); text-&gt;insertHtml("&lt;p&gt;test test test test test test&lt;/p&gt;&lt;p&gt;|||||||||&lt;/p&gt;"); text-&gt;show(); text-&gt;setFixedWidth(text-&gt;document()-&gt;idealWidth() + text-&gt;contentsMargins().left() + text-&gt;contentsMargins().right()); } };
    • 我添加了一个带有insertHTML()setFixedWidth() 调用的按钮,每次添加示例的HTML 时,QTextEdit 都会缩小一点。我是否在布局设置或 QTextEdit 本身中缺少某些内容?