PDA

View Full Version : How can i achieve an auto-resizing QStackedWidget?



truefusion
28th February 2010, 01:44
Whenever a widget on a different index is shown (i.e. whenever currentChanged(int) is emitted), i would like for the stackedwidget to resize itself according to the minimize size of the current widget. By default, QStackedWidget uses the biggest widget in the stack to determine the size of the stackedwidget. I have tried multiple attempts, ranging from size policies, size constraints to size hints, both from the stackedwidget itself to even the child widgets in hopes of achieving the desired function. Unfortunately, nothing i have tried worked.

Assume at least the following structure:


QStackedWidget * stackedwidget = new QStackedWidget;

stackedwidget->addWidget(new QWidget);
stackedwidget->addWidget(new QWidget);

stackedwidget->widget(0)->setMinimumHeight(100);
stackedwidget->widget(1)->setMinimumHeight(200);

What would i have to do in order to achieve my goal? I am out of ideas.

truefusion
28th February 2010, 23:35
So i have decided to create my own simple "stacked widget" and it seems to work fine. For anyone interested:

Definition:


#include <QList>
#include <QWidget>

class StackedWidget : public QWidget
{
Q_OBJECT

public:
StackedWidget(QWidget * = 0, Qt::WindowFlags = 0);

void addWidget(QWidget *);
int count();
QWidget * currentWidget();

void setAutoResize(bool yes)
{ auto_resize = yes; }

QSize sizeHint();

protected:
void showCurrentWidget();

private:
bool auto_resize;
int curr_index;
QList<QWidget *> widgets;

public slots:
void setCurrentIndex(int);
};


Implementation:


#include <QVBoxLayout>

StackedWidget::StackedWidget(QWidget * parent, Qt::WindowFlags f)
: QWidget(parent, f),
curr_index(0)
{
QVBoxLayout * layout = new QVBoxLayout(this);
}

int StackedWidget::count()
{ return widgets.count(); }

void StackedWidget::addWidget(QWidget * w)
{
widgets.append(w);
layout()->addWidget(w);
showCurrentWidget();
}

QWidget * StackedWidget::currentWidget()
{ return widgets.at(curr_index); }

void StackedWidget::setCurrentIndex(int i)
{
curr_index = i;
showCurrentWidget();
}

void StackedWidget::showCurrentWidget()
{
if (widgets.count() > 0)
{
foreach (QWidget * widget, widgets)
widget->hide();

widgets.at(curr_index)->show();
updateGeometry();
}
}

QSize StackedWidget::sizeHint()
{
if (auto_resize
&& count() > 0)
return currentWidget()->minimumSize();
else
return QWidget::sizeHint();
}

sstotok
17th May 2010, 02:31
Thanks truefusion. It works for me. However, I believe the code posted is your first draft :) E.g. I believe 'layout' in the constructor should be a member, not just local var.

I have a question (apologize since I'm new to Qt), how and where should we release the memory in heap as it is claimed by QList<QWidget *> widgets; ?