gpt4 book ai didi

c++ - qtextedit - 调整大小以适应

转载 作者:IT老高 更新时间:2023-10-28 23:17:33 26 4
gpt4 key购买 nike

我有一个 QTextEdit它充当“显示器”(可编辑为假)。它显示的文本是自动换行的。现在我确实希望设置此文本框的高度,以便文本完全适合(同时也尊重最大高度)。

基本上,布局下方的小部件(在相同的垂直布局中)应该获得尽可能多的空间。

怎样才能最容易地做到这一点?

最佳答案

我使用 QFontMetrics 找到了一个非常稳定、简单的解决方案!

from PyQt4 import QtGui

text = ("The answer is QFontMetrics\n."
"\n"
"The layout system messes with the width that QTextEdit thinks it\n"
"needs to be. Instead, let's ignore the GUI entirely by using\n"
"QFontMetrics. This can tell us the size of our text\n"
"given a certain font, regardless of the GUI it which that text will be displayed.")

app = QtGui.QApplication([])

textEdit = QtGui.QPlainTextEdit()
textEdit.setPlainText(text)
textEdit.setLineWrapMode(True) # not necessary, but proves the example

font = textEdit.document().defaultFont() # or another font if you change it
fontMetrics = QtGui.QFontMetrics(font) # a QFontMetrics based on our font
textSize = fontMetrics.size(0, text)

textWidth = textSize.width() + 30 # constant may need to be tweaked
textHeight = textSize.height() + 30 # constant may need to be tweaked

textEdit.setMinimumSize(textWidth, textHeight) # good if you want to insert this into a layout
textEdit.resize(textWidth, textHeight) # good if you want this to be standalone

textEdit.show()

app.exec_()

(请原谅我,我知道你的问题是关于 C++ 的,而且我使用的是 Python,但在 Qt 中它们几乎是一回事)。

关于c++ - qtextedit - 调整大小以适应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9506586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com