Why Qt::AlignTop doesn't work in QVBoxLayout that I use like main layout?

752 Views Asked by At

I have simple class that inherits QDialog, I add dynamically elements and my elements are located in the center, but I want to add them at the top.

class CustomDialog : public QDialog {
    Q_OBJECT
private:
    QVBoxLayout *mainLayout;
CustomDialog() 
{
     mainLayout = new QVBoxLayout();
    setLayout(mainLayout);
}
public:
    void update() 
   {
    QLabel* label = new QLabel("some text");

    QVBoxLayout *verLayout = new QVBoxLayout;
    verLayout->addStretch();
    verLayout->setAlignment(Qt::AlignTop);

    verLayout->addWidget(label, Qt::AlignTop); 
    mainLayout->setAlignment(Qt::AlignTop);
    mainLayout->addLayout(verLayout, Qt::AlignTop);
    }
};

What am I doing wrong? and why my dynamically added elements always in center?

1

There are 1 best solutions below

0
On

I understand that you want to place it and that the top is shown, so you could use QSpacerItem to push it.

class CustomDialog : public QDialog {
    Q_OBJECT
    QVBoxLayout *mainLayout;

public:
    CustomDialog(QWidget *parent=0): QDialog(parent)
    {
        mainLayout = new QVBoxLayout(this);

        QSpacerItem *verticalSpacer = new QSpacerItem(20, 217, QSizePolicy::Minimum, QSizePolicy::Expanding);
        mainLayout->addItem(verticalSpacer);

        addWidgets("1");
        addWidgets("2");
    }
private:
    void addWidgets(const QString &text)
    {
        QLabel* label = new QLabel(text);

        QVBoxLayout *verLayout = new QVBoxLayout;
        verLayout->addStretch();
        verLayout->setAlignment(Qt::AlignTop);

        verLayout->addWidget(label, Qt::AlignTop);
        mainLayout->setAlignment(Qt::AlignTop);
        mainLayout->insertLayout(mainLayout->count()-1, verLayout);
    }
};

enter image description here

Or if you want it to have a reverse order you must insert it in the first position with:

mainLayout->insertLayout(0, verLayout);

enter image description here

Note: The use of addLayout is incorrect since the second parameter is stretch.