qtextedit - 调整大小以适应

14
我有一个 QTextEdit,它充当“显示器”(不可编辑)。它显示的文本是自动换行的。现在我想设置此文本框的高度,以便文本恰好适合其中(同时也要遵守最大高度)。
基本上,在相同的垂直布局中,该布局下方的窗口小部件应尽可能获得更多的空间。
如何最轻松地实现这一点?

1
在QT库中找不到QTextBox。 - Dmitriy Kachko
指的是QTextEdit,已修复(附链接) - paul23
如果您将QTextEdit放置在另一个QScrollArea中(以设置最大高度),则可以使用我在此处提供的相同代码:http://stackoverflow.com/questions/7301785/react-on-the-resizing-of-a-qmainwindow-for-adjust-widgets-size - alexisdm
1
@paul23 你可能想要查看我在类似请求中的答案 这里 - laurasia
5个回答

12

我发现一个相当稳定,简洁的解决方案,使用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 ++的,但我在Qt中使用的是Python,但无论如何它们基本上是相同的)。


2

可以通过以下方式获取基础文本的当前大小

QTextEdit::document()->size();

我相信使用这种方法我们可以相应地调整小部件的大小。
#include <QTextEdit>
#include <QApplication>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextEdit te ("blah blah blah blah blah blah blah blah blah blah blah blah");
    te.show();
    cout << te.document()->size().height() << endl;
    cout << te.document()->size().width() << endl;
    cout <<  te.size().height() << endl;
    cout <<  te.size().width() << endl;
// and you can resize then how do you like, e.g. :
    te.resize(te.document()->size().width(), 
              te.document()->size().height() + 10);
    return a.exec();    
}

转换为“文档”时,自动换行不会丢失,对吧? - paul23
尝试编译我在答案中提供的代码,你会看到小部件的大小和包含文档的大小之间的差异。换行不会丢失。但是你需要先显示小部件。 - Dmitriy Kachko
嗯,这并不真正起作用 - 因为在使用setText()命令时大小没有被设置。 - paul23
你需要先显示小部件才能形成文档。实际上,这是一种不好的编程风格,因为QT中小部件的大小实际上取决于小部件的外部布局和大小策略,但是你仍然可以使用这个想法。 - Dmitriy Kachko

2

除非您需要QTextEdit的特定功能,否则打开自动换行的QLabel将完全满足您的需求。


5
qlabel只能在单词边界处自动换行,当数据过大时也不会显示滚动条。我一开始使用了一个标签,但似乎我需要两个功能集... - paul23

1
在我的情况下,我将我的QLabel放置在QScrollArea中。如果你有兴趣,你可以将它们结合起来创建自己的小部件。

0
说起 Python,我发现 .setFixedWidth( your_width_integer ).setFixedSize( your_width, your_height ) 非常有用。不确定 C 是否有类似的窗口小部件属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接