PDA

View Full Version : Difference of Programming Style



alphazero
16th November 2010, 14:01
Dear All,

I am beginner in Qt, and wanna ask about programming style :

What's difference of :

QDialog xdialog(this);
QHBoxLayout myLayout ;
myLayout.addWidget(widget,0,0);
dialog.setLayout(myLayout); // error happened

with

QDialog xdialog(this);
QHBoxLayout *myLayout = new QHBoxLayout;
myLayout->addWidget(widget,0,0);
xdialog.setLayout(myLayout); // no error occurs


Why we use 1st script, it returns error ? How to fix it if we want to use 1st script too ?

Thanks

Zlatomir
16th November 2010, 14:23
It's all about what parameter the setLayout(...) (http://doc.qt.nokia.com/4.7/qwidget.html#setLayout) expects.
To correct the first "script" you can call it like this: xdialog.setLayout(&myLayout);

But in most of the cases you need the layouts and widgets on the heap (use the pointers and new to allocate memory), maybe you should read about dynamic memory allocation in C++ first.

LE: this isn't about programming style, it's about what life-time of objects you need (stack or heap) and usage of pointers.

wladek
16th November 2010, 14:30
Hi alphazero,

If you look at the QWidget::setLayout documentation you will see that this function expects a pointer to a QLayout.

The 2nd option that you are presenting works just because of this, because you are using a pointer. And this is the best way to do it.

If you still want to use the 1st option, we can give the function what it expects.
Do this by :
dialog.setLayout(&myLayout);

Regards,
Wladek

alphazero
16th November 2010, 14:59
Hi Zlatomir and wladek
thanks for your fast replies,

it works using & , and I still learning about C++ and Qt too..

Timoteo
16th November 2010, 15:30
I tend to favor compact code so what you presented would look more like

QDialog xdialog(this);
xdialog.setLayout(new QGridLayout);
xidalog.layout()->addWidget(someWidgetPtr);


and that IS about style.