qtextedit - 调整大小以适应

时间:2012-02-29 21:04:53

标签: c++ qt qtextedit

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

基本上布局下面的小部件(在相同的垂直布局中)应该尽可能多地占用空间。

如何最轻松地实现这一目标?

5 个答案:

答案 0 :(得分:9)

我使用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他们反正几乎是一样的。)

答案 1 :(得分:2)

除非您需要QTextEdit的功能特别具体,否则启用自动换行功能的QLabel将完全符合您的要求。

答案 2 :(得分:1)

可以通过

获取基础文本的当前大小
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();    
}

答案 3 :(得分:0)

说到Python,我实际上发现.setFixedWidth( your_width_integer ).setFixedSize( your_width, your_height )非常有用。不确定C是否具有类似的小部件属性。

答案 4 :(得分:0)

在我的情况下,我把我的QLabel放在QScrollArea中。如果你很热衷,你可以将两者结合起来制作自己的小部件。

相关问题