QHBoxLayout布局中的项重叠

时间:2014-03-19 22:09:44

标签: c++ qt layout qt5

我无法弄清楚Qt有什么问题。我正在尝试创建一个简单的布局,如下所示:

+-------+-----------+
|       | Label1    |
| Thumb |-----------+
|       | Label2    |
|       |(multiline)|
+-------+-----------+

这是执行此操作的代码:

    labelInfoName = new QLabel("Sample name", this);
    labelInfoDetails = new QLabel("Sample details...", this);
    labelInfoDetails->setAlignment(static_cast<Qt::Alignment>(Qt::AlignTop | Qt::AlignLeft));

    QVBoxLayout* textInfoLayout = new QVBoxLayout(this);
    textInfoLayout->addWidget(labelInfoName);
    textInfoLayout->addWidget(labelInfoDetails, 1);

    // Create info pane
    imgInfoThumbnail = new QLabel(this);
    imgInfoThumbnail->setFixedSize(64, 64);
    imgInfoThumbnail->setStyleSheet("background: black;");

    QHBoxLayout* infoLayout = new QHBoxLayout(this);
    infoLayout->addWidget(imgInfoThumbnail);
    infoLayout->addLayout(textInfoLayout, 1)

    this->setLayout(infoLayout);

thisQWidget。这是在从QWidget派生的类中设置布局的代码。然后我想将它显示为可停靠的小部件,我从QMainWindow类中这样做:

    widget = new Widget(this); // Widget that was set up above
    QDockWidget* dockWidget = new QDockWidget("Project", this);
    dockWidget->setWidget(widget);
    addDockWidget(Qt::LeftDockWidgetArea, dockWidget);

但这是我得到的:

what I get instead

我需要将小部件作为自定义控件放在任何地方。以前,它被定义为QDockWidget,而不是调用this->setLayout()我创建了一个QWidget对象,这可以按预期工作:

    QWidget* widget = new QWidget(this);
    widget->setLayout(infoLayout);
    this->setWidget(widget);

但是我现在的方式已经完成了,它将它们放在了彼此之上。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您正在错误地创建布局。

将父(窗口小部件)传递给布局时,此布局会自动设置为此窗口小部件的布局。 问题是,一旦为小部件设置了布局,就无法更改,我很确定你会收到一些警告。

因此,在构建布局时(至少在第一种情况下)删除this

labelInfoName = new QLabel("Sample name", this);
labelInfoDetails = new QLabel("Sample details...", this);
labelInfoDetails->setAlignment(static_cast<Qt::Alignment>(Qt::AlignTop | Qt::AlignLeft));

QVBoxLayout* textInfoLayout = new QVBoxLayout();
textInfoLayout->addWidget(labelInfoName);
textInfoLayout->addWidget(labelInfoDetails, 1);

// Create info pane
imgInfoThumbnail = new QLabel(this);
imgInfoThumbnail->setFixedSize(64, 64);
imgInfoThumbnail->setStyleSheet("background: black;");

QHBoxLayout* infoLayout = new QHBoxLayout(this);
infoLayout->addWidget(imgInfoThumbnail);
infoLayout->addLayout(textInfoLayout, 1)

this->setLayout(infoLayout);