PDA

View Full Version : keeping a widget to be square



jmsbc
28th May 2009, 02:28
Hello,

I have a problem with placing a widget into a horizontalLayout and making it keep an equal aspect ratio (square).

Here is a rough outline of my code:


TargetDisplay::TargetDisplay(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
d_plot = new RandomPlot(this);

QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred);
policy.setHeightForWidth(true);
d_plot->setSizePolicy(policy);

ui.horizontalLayout->insertWidget(0, d_plot);
}


and then in my RandomPlot widget I have:



class RandomPlot: public QWidget
{
Q_OBJECT

public:
RandomPlot(QWidget *parent);
~RandomPlot();

int heightForWidth(int w) const {
return w;
}
}


but my widget is not maintaining an equal aspect ratio. Can somebody please tell me what I'm doing wrong? Thank you!

-James

wysota
28th May 2009, 08:51
This will only work for a widget in a layout. For a top-level window you have to reimplement resizeEvent() and resize the widget to a proper aspect from within.

jmsbc
28th May 2009, 17:42
This will only work for a widget in a layout. For a top-level window you have to reimplement resizeEvent() and resize the widget to a proper aspect from within.
My widget is in HorizontalLayout:


ui.horizontalLayout->insertWidget(0, d_plot);

Can somebody explain what I need to add to my original code? Thanks

jmsbc
29th May 2009, 02:19
Nevermind, I figured it out. Instead of adding d_plot directly to the horizontalLayout, I added it to QwtDynGridLayout first, and then added the layout to the horizontalLayout:



gLayout = new QwtDynGridLayout(this);
gLayout->addWidget(d_plot);
ui.horizontalLayout->insertLayout(0, gLayout);


Now I get a square

luf
16th June 2009, 14:40
It's because the stretch factor on your horizontal layout when adding the widget is by default 0.

QHBoxLayout *hbox = new QHBoxLayout();
hbox->addWidget(mywidget, 1);

If you are using Qt Designer, set the layoutStretch parameters.

luf
16th June 2009, 20:47
As I found this layout manager that keeps a widgets square, I figured it would be wise to share it:
http://wiki.forum.nokia.com/index.php/CS001309_-_Maintaining_square_form_for_a_widget_in_Qt

Attached a zip file with source and example, in case it goes missing on the wiki.

Thanks to the heads at nokia for making this layout manager :)