[Qt-interest] can not set Layout correctly

Bo Thorsen bo at fioniasoftware.dk
Wed Aug 25 10:27:56 CEST 2010


Den 25-08-2010 09:29, yanqzhi at gmail.com skrev:
> I hnow that If there already is a layout manager installed on this 
> widget, QWidget
> won't let you install another.
> 
> But I do not set layout in the MyDialog and other class except for in 
> the class
> TestDialog's constructor;
> 
> I want to hnow how set layout correctly!

Ok, there's one other thing you didn't think of: When creating a layout
with a QWidget as parent, the layout is set on the parent. Here is the
source code for the QLayout constructor:

QLayout::QLayout(QWidget *parent)
    : QObject(*new QLayoutPrivate, parent)
{
    if (!parent)
        return;
    parent->setLayout(this);
}

When creating widgets and layouts, it's usually best not to give them
any parent in the constructor, as this is done when you place them in
the widget tree.

So instead of your code (repeated here):

mButton1 = new QPushButton("right", this);
mRightLayou = new QGridLayout(this);
mRightLayou->addWidget(mButton1, 0, 0, 1, 1);

mHLayout = new QHBoxLayout(this);
mHLayout->addLayout(mLayout);
mHLayout->addLayout(mRightLayou);

setLayout(mHLayout);

... you should create the code like this:

mButton1 = new QPushButton("right");
mRightLayou = new QGridLayout;
mRightLayou->addWidget(mButton1, 0, 0, 1, 1);

mHLayout = new QHBoxLayout(this);
mHLayout->addLayout(mLayout);
mHLayout->addLayout(mRightLayou);

And mLayout should also be constructed without a parent.

I know this looks odd to a Qt coder, but that's the proper Qt 4 way.

I hope this helps.

Bo.

-- 

Bo Thorsen, Fionia Software
Expert Qt and C++ developer for hire
Mail me if you need a hand with your Qt code



More information about the Qt-interest-old mailing list