2

我如何对 a 的调整大小做出反应QMainWindow?我有QTextBrowsers一个QScrollArea,我在创建它们时将它们调整为内容的大小(唯一应该滚动的是QScrollArea)。

现在一切正常,但是如果我调整 的大小mainWindow,则不会更改 的高度QTextBrowsers,因为不会触发回流功能。

你有什么更好的想法来调整QTextBrowser它的内容吗?我目前的代码是:

void RenderFrame::adjustTextBrowser(QTextBrowser* e) const {
    e->document()->setTextWidth(e->parentWidget()->width());
    e->setMinimumHeight(e->document()->size().toSize().height());
    e->setMaximumHeight(e->minimumHeight());
}

parentWidget()是必要的,因为width()在小部件本身上运行总是返回 100,无论实际大小如何。

4

1 回答 1

3

如果只有文本或 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();
    }
};
于 2011-09-05T00:06:14.383 回答