首页 > 解决方案 > 元素不显示在对话框上

问题描述

我正在尝试使用 QT 实现一个对话框。这是我第一次写一个对话框而不是使用设计器。这是因为此对话框将包含一些字段,这些字段将取决于是否出现某些选择。

到目前为止,我遵循本指南,但将其用于我自己的字段: https ://www.informit.com/articles/article.aspx?p=1405224

当我运行应用程序时,不知何故我的元素(LineEdit 和 Lable)没有出现在对话框中。我没有得到我真正缺少的东西。我是否需要以某种方式将元素添加到代码上的对话框中?

这是我的头文件:

    #ifndef PLANETARYVIEW_H
    #define PLANETARYVIEW_H
    #include <QDialog>
    #include <QVBoxLayout>
    #include <QLabel>
    #include <QLineEdit>
    #include <QComboBox>

    class PlanetaryView : public QDialog

    {
        Q_OBJECT
    public:
        explicit PlanetaryView(QWidget *parent = nullptr);

    private:
        QVBoxLayout* PlanetsVLayout;
        QLabel* PlanetLabel;
        QLineEdit* PlanetLineEdit;
   };

   #endif // PLANETARYVIEW_H

那是我的cpp文件

   #include "planetaryview.h"

       PlanetaryView::PlanetaryView(QWidget *parent)
       :QDialog(parent)
  {
       PlanetsVLayout = new QVBoxLayout();

       PlanetLineEdit = new QLineEdit();
       PlanetsVLayout->addWidget(PlanetLineEdit);

       PlanetLabel = new QLabel("Planet:");
       PlanetLabel->setBuddy(PlanetLineEdit);
       PlanetsVLayout->addWidget(PlanetLabel);

  }

想法是让 Lable 和 LineEdit 在对话框中彼此相邻。

标签: c++qt5qdialog

解决方案


问题是布局没有分配给小部件,解决方案是

PlanetsVLayout = new QVBoxLayout(this);

或者

PlanetsVLayout = new QVBoxLayout();
setLayout(PlanetsVLayout);

推荐阅读