Qt自定义控件未显示子控件

3
我是一名有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:

我有一个自定义小部件,其中包含一些标准子小部件。如果我创建一个单独的测试项目,并重新定义我的自定义小部件以继承QMainWindow,则一切正常。但是,如果我的自定义小部件继承自QWidget,则窗口会打开,但内部没有子小部件。

这是代码:

controls.h:

#include <QtGui>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QPushButton>

class Controls : public QWidget
{
    Q_OBJECT

public:
    Controls();

private slots:
    void render();

private:
    QWidget *frame;
    QWidget *renderFrame;
    QVBoxLayout *layout;
    QLineEdit *rayleigh;
    QLineEdit *mie;
    QLineEdit *angle;
    QPushButton *renderButton;
};

controls.cpp:

#include "controls.h"

Controls::Controls()
{
    frame = new QWidget;
    layout = new QVBoxLayout(frame);

    rayleigh = new QLineEdit;
    mie = new QLineEdit;
    angle = new QLineEdit;
    renderButton = new QPushButton(tr("Render"));

    layout->addWidget(rayleigh);
    layout->addWidget(mie);
    layout->addWidget(angle);
    layout->addWidget(renderButton);

    frame->setLayout(layout);
    setFixedSize(200, 400);

    connect(renderButton, SIGNAL(clicked()), this, SLOT(render()));
}

main.cpp:

#include <QApplication>
#include "controls.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    Controls *controls = new Controls();
    controls->show();

    return app.exec();
}

这将打开一个具有正确尺寸但没有内容的窗口。

请记住,这是我使用Qt的第一天。我需要使其在不继承QMainWindow的情况下工作,因为我以后需要将其放在QMainWindow上。

2个回答

3
您缺少一个顶层布局:
Controls::Controls()
{
    ... (yoour code)

    QVBoxLayout* topLevel = new QVBoxLayout(this);
    topLevel->addWidget( frame );
}

或者,如果该框架未在其他地方使用,可以直接使用:
Controls::Controls()
{
    layout = new QVBoxLayout(this);

    rayleigh = new QLineEdit;
    mie = new QLineEdit;
    angle = new QLineEdit;
    renderButton = new QPushButton(tr("Render"));

    layout->addWidget(rayleigh);
    layout->addWidget(mie);
    layout->addWidget(angle);
    layout->addWidget(renderButton);

    setFixedSize(200, 400);

    connect(renderButton, SIGNAL(clicked()), this, SLOT(render()));
}

请注意,当创建QLayout时(使用父窗口小部件),setLayout将自动完成。

谢谢,解决了 :) - dnmh

1

您需要在Controls类上设置布局来管理其子项的大小。我建议移除您的框架小部件。

controls.cpp

Controls::Controls()
{
  layout = new QVBoxLayout(this);
  .
  .
  .
}

main.cpp

int main(int argc, char* argv[])
{
  QApplication app(argc, argv);

  MainWindow w;

  w.show();

  return app.exec();
}

谢谢,现在没问题了 :) - dnmh
没问题,如果你在Qt Creator中将其声明为指针并按下'.',它会自动变成'->'。 - dnmh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接