PDA

View Full Version : QTextEdit auto resize



bunjee
26th October 2007, 14:51
Hey there,

I'm displaying some text into a read only QTextEdit.

Is there a way to set the widget to Auto resize depending on the length of text ?

wysota
26th October 2007, 15:28
If you reimplement sizeHint() to take into consideration the size of the document and call updateGeometry() whenever the document content changes then yes.

bunjee
26th October 2007, 17:33
Okay here is a first implementation which doesn't seem to work as expected :


ZeParagraphWidget::ZeParagraphWidget(const QString & string,
QWidget *parent) :
QTextEdit("", parent)
{
// Size policy
QSizePolicy localSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
setSizePolicy(localSizePolicy);

setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOf f);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff) ;
}

void ZeParagraphWidget::setText(const QString & text)
{
ZeLog::get()->Print("ZeParagraphWidget - setText\n");

QTextEdit::setText(text);

updateGeometry();
}

/* virtual */ QSize ZeParagraphWidget::sizeHint() const
{
QSize sizeRect(document()->idealWidth(), document()->size().height());

return sizeRect;
}

By default the box is way to large, and the width doesn't fit the text.
I'm not sure about the size policy too.

wysota
26th October 2007, 19:19
No, it won't work that way. First of all you have to include the widget frame in your calculations. And second of all, if you calculate a width of a document, you must set it first before calling size().height(). Or don't use idealWidth (because it may return a value smaller than you need) just return document()->size() extended by the size of the widget decoration.

bunjee
26th October 2007, 20:59
The following is working good in my case:


//================================================== ===========================
//================================================== ===========================

/* virtual */ int ZeParagraphWidget::heightForWidth(int w) const
{
ZeLog::get()->Print("ZeParagraphWidget - heightForWidth %d %f\n", w, document()->size().height());

return (int) (document()->size().height());
}

//================================================== ===========================
//================================================== ===========================
// Slots
//================================================== ===========================
//================================================== ===========================

void ZeParagraphWidget::onContentsChanged()
{
ZeLog::get()->Print("ZeParagraphWidget - onContentsChanged\n");

updateGeometry();
}