问题
How do I react on the resize of a QMainWindow
? I have QTextBrowsers
in a QScrollArea
and I adjust them to the size of the content on creating them (the only thing that should scroll is the QScrollArea
).
Everything works for now, but if I resize the mainWindow
, the height of the QTextBrowsers
isn't changed, because the reflow function isn't triggered.
Do you have any better idea to adjust a QTextBrowser
to it's content? My current code is:
void RenderFrame::adjustTextBrowser(QTextBrowser* e) const {
e->document()->setTextWidth(e->parentWidget()->width());
e->setMinimumHeight(e->document()->size().toSize().height());
e->setMaximumHeight(e->minimumHeight());
}
The parentWidget()
is necessary because running width()
on the widget itself returns always 100, regardless of the real size.
回答1:
If there is only text or html, you could use QLabel
instead, because it already adapts its size to the available space. You'll have to use:
label->setWordWrap(true);
label->setTextInteractionFlags(Qt::TextBrowserInteraction);
to have almost the same behavior as a QTextBrowser
.
If you really want to use a QTextBrowser
, you can try something like this (adapted from QLabel
source code):
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();
}
};
来源:https://stackoverflow.com/questions/7301785/react-on-the-resizing-of-a-qmainwindow-for-adjust-widgets-size