Pregunta

¿Cómo reacciono en el cambio de tamaño de un QMainWindow? tengo QTextBrowsers en un QScrollArea y los ajusto al tamaño del contenido para crearlos (lo único que debería desplazar es el QScrollArea).

Todo funciona por ahora, pero si redimensiono el mainWindow, la altura del QTextBrowsers no se cambia, porque la función de reflujo no se activa.

¿Tiene alguna mejor idea para ajustar un QTextBrowser a su contenido? Mi código actual es:

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

los parentWidget() es necesario porque correr width() En el widget en sí regresa siempre 100, independientemente del tamaño real.

¿Fue útil?

Solución

Si solo hay texto o html, puede usar QLabel En cambio, porque ya adapta su tamaño al espacio disponible. Tendrás que usar:

label->setWordWrap(true);        
label->setTextInteractionFlags(Qt::TextBrowserInteraction); 

tener casi el mismo comportamiento que un QTextBrowser.


Si realmente quieres usar un QTextBrowser, puedes probar algo como esto (adaptado de QLabel código fuente):

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();
    }
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top