dnmh
dnmh

Reputation: 2135

Qt custom widget not showing child widgets

I have a custom widget with some standard child widgets inside. If I make a separate test project and redefine my custom widget to inherit QMainWindow, everything is fine. However, if my custom widget inherits QWidget, the window opens, but there are no child widgets inside.

This is the code:

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();
}

This opens up a window with correct dimensions, but with no content inside.

Bear in mind this is my first day using Qt. I need to make this work without inheriting QMainWindow because later on I need to put this on a QMainWindow.

Upvotes: 3

Views: 4720

Answers (2)

Andrew Dolby
Andrew Dolby

Reputation: 809

You'll want to set a layout on your Controls class for managing its child sizes. I'd recommend removing your frame widget.

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();
}

Upvotes: 1

jpo38
jpo38

Reputation: 21564

You're missing a top level layout:

Controls::Controls()
{
    ... (yoour code)

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

Or, if frame is not used anywhere else, directly:

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()));
}

Note that setLayout is done automatically when QLayout is created (using parent widget)

Upvotes: 3

Related Questions