html - 调整 QT 的 QTextEdit 大小以匹配文本宽度

标签 html css qt qtextedit

我有一个 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 的宽度)以在不使用水平滚动条的情况下显示整行文本?

最佳答案

您可以使用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());

结果:

screenshot

关于html - 调整 QT 的 QTextEdit 大小以匹配文本宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21466539/

相关文章:

jquery - IOS html css Z-Index 和位置绝对不适用于重叠的 DIV

css - 如何防止 CSSTidy 删除 *property IE7 Hack? (或另一个独立工具)

css - Firefox/Mac 的 Helvetica Neue 基线渲染问题

windows - 检查 Qt 在运行时使用哪个 OpenGL 引擎进行发布构建

c++ - 无法在 Win32 Release模式下编译 Qt 应用程序

css - 图片标题适合屏幕

javascript - 如何使用 javascript/ajax 将图像 URL 转换为 DOM 文件对象?

javascript - 在javascript中使用数组查找最大数字

javascript - 使用 JS 禁用打印

c++ - 在不读取下一个字节的情况下解压缩连接的 zlib 流