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

标签 c++ qt qtextedit

我有一个 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/

相关文章:

C++ MPI 创建和发送具有字段 char[16] 和整数的结构数组

c++ - = txtSelect->GetValue(); C++,段错误。这很奇怪

用于 Mac 上 Qt 的 MySQL

QTextEdit减少 "tab"键的缩进

python - 将 QTextEdit 的内容保存为 *.pdf?

c++ - QTextEdit 中的水平线

c++ - 我编译的 C++ 程序太小。我怎样才能让它变大?

c++ - 将模板类作为一般参数,不指定模板参数

c++ - 在发出要在程序中使用的命令时如何获取终端的输出?

c++ - 大理石 window 汇编