gpt4 book ai didi

c++ - QHBoxLayout 布局中的项目重叠

转载 作者:行者123 更新时间:2023-11-28 02:53:34 28 4
gpt4 key购买 nike

我不知道 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);

this 是一个QWidget。这是在派生自 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);

但我现在的做法是,将它们放在彼此之上。我做错了什么?

最佳答案

您创建的布局不正确。

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

因此在构造布局时(至少在第一种情况下)只需删除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);

关于c++ - QHBoxLayout 布局中的项目重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519217/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com