【问题标题】:Items in QHBoxLayout layout overlapQHBoxLayout 布局中的项目重叠
【发布时间】:2014-04-26 11:40:15
【问题描述】:

我无法弄清楚 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);

但这是我得到的:

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

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

但我现在的做法是让它们相互叠加。我做错了什么?

【问题讨论】:

    标签: c++ qt layout qt5


    【解决方案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);
    

    【讨论】:

    • 就是这样,谢谢。还有一个问题:Qt 会自动释放所有这些分配的对象,还是我必须删除它们?我一直认为将'this'作为父级传递会使所有这些分配的对象在'this'被销毁时被释放。
    • 是的,它将被释放。简单的布局必须有一个父小部件(不需要直接)。当您分配布局时,其中的所有项目都会重新分配给相应的小部件。您可以检查parent 小部件的值或parentWidget 的布局所有将指向相同this
    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多