c++ - 为什么 Qt::AlignTop 在我像主布局一样使用的 QVBoxLayout 中不起作用?

标签 c++ qt qt5 qvboxlayout

我有继承QDialog的简单类,我动态添加元素 我的元素位于中心,但我想将它们添加到顶部。

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);
    }
};

我做错了什么?为什么我动态添加的元素总是居中?

最佳答案

我知道您想放置它并且显示了顶部,因此您可以使用 QSpacerItem 来插入它。

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

或者如果你想让它有一个相反的顺序,你必须将它插入到第一个位置:

mainLayout->insertLayout(0, verLayout);

enter image description here

注意:使用addLayout不正确,因为第二个参数是 stretch

关于c++ - 为什么 Qt::AlignTop 在我像主布局一样使用的 QVBoxLayout 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45338820/

相关文章:

qt - 在没有指针的情况下在 Qt 中 move 语义?

c++ - 静态类成员,这是一个结构

c++ - Recvfrom 在本地工作,但在执行之间的随机端口上不接收任何内容

c++ - 在 Qt 服务器上验证用户

c++ - QWebView : print problems

c++ - 在QT应用程序中制作一个透明孔

c++ - 如果两次调用析构函数,为什么我的程序不会崩溃

c++ - 鉴于此示例,与使用多线程或进程相比,轮询设计对我有何好处?

c++ - 在 qt C++ 中从 mysql 创建一个动态数据结构

c++ - 在运行时将更改环境变量应用于应用程序