get the exact height of QTextDocument in pixels

淺唱寂寞╮ 提交于 2019-12-04 19:42:49

So I finally found a solution but it is really ugly. If anyone knows anything better, please publish it.

from PyQt5.QtWidgets import QApplication, QPlainTextEdit

app = QApplication([])
w = QPlainTextEdit()
# test various formatting
w.appendHtml("<h1>Hello!</h1>")
w.appendHtml("<b>Hello!</b>")
w.appendPlainText("Hello!")
doc = w.document()
layout = doc.documentLayout()
h = 0
b = doc.begin()
while b != doc.end():
    h += layout.blockBoundingRect(b).height()
    b = b.next()

# magic formula: I do not know why the document margin is already
# once included in the height of the last block, and I do not know
# why there must be the number 1 at the end... but it works
w.setFixedHeight(h + doc.documentMargin() + 2 * w.frameWidth() + 1)

w.show()
app.exec_()

So this should show the box without scroll bar. If you decrease the height by 1, the scroll bar appears. This should work with any number of lines, document margins, frame widths, formatting etc. Hopefully.

Shot in the dark without testing

Have you looked @ pageSize?

From the docs:

This property holds the page size that should be used for laying out the document

The units are determined by the underlying paint device. The size is measured in logical pixels when painting to the screen, and in points (1/72 inch) when painting to a printer.

By default, for a newly-created, empty document, this property contains an undefined size.

If you set the pageSize, as directed by the other thread, I'd expect you'd get the value out in the pixels that QPlainTextEdit::setMinimumHeight needs.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!