如果只有文本或 html,则可以QLabel
改用,因为它已经根据可用空间调整其大小。你必须使用:
label->setWordWrap(true);
label->setTextInteractionFlags(Qt::TextBrowserInteraction);
具有与 a 几乎相同的行为QTextBrowser
。
如果你真的想使用 a QTextBrowser
,你可以尝试这样的事情(改编自QLabel
源代码):
class TextBrowser : public QTextBrowser {
Q_OBJECT
public:
explicit TextBrowser(QWidget *parent) : QTextBrowser(parent) {
// updateGeometry should be called whenever the size changes
// and the size changes when the document changes
connect(this, SIGNAL(textChanged()), SLOT(onTextChanged()));
QSizePolicy policy = sizePolicy();
// Obvious enough ?
policy.setHeightForWidth(true);
setSizePolicy(policy);
}
int heightForWidth(int width) const {
int left, top, right, bottom;
getContentsMargins(&left, &top, &right, &bottom);
QSize margins(left + right, top + bottom);
// As working on the real document seems to cause infinite recursion,
// we create a clone to calculate the width
QScopedPointer<QTextDocument> tempDoc(document()->clone());
tempDoc->setTextWidth(width - margins.width());
return qMax(tempDoc->size().toSize().height() + margins.height(),
minimumHeight());
}
private slots:
void onTextChanged() {
updateGeometry();
}
};