qtextedit-根据需要调整大小

qtextedit - resize to fit

本文关键字:调整 qtextedit-      更新时间:2023-10-16

我有一个QTextEdit,它充当"displayer"(可编辑为false)。它显示的文本是换行的。现在,我确实希望设置这个文本框的高度,使文本完全适合(同时也考虑最大高度)。

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

如何最容易做到这一点?

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

from PyQt4 import QtGui
text = ("The answer is QFontMetricsn."
        "n"
        "The layout system messes with the width that QTextEdit thinks itn"
        "needs to be.  Instead, let's ignore the GUI entirely by usingn"
        "QFontMetrics.  This can tell us the size of our textn"
        "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中,它们几乎是一样的)。

除非QTextEdit的功能有什么特别的需要,否则打开换行符的QLabel将完全满足您的要求。

可以通过获得底层文本的当前大小

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();    
}

在我的例子中,我将QLabel放在QScrollArea中。如果你感兴趣,你可以将两者结合起来,制作自己的小工具。

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