qtqwidgetqmainwindow

Widgets added to a QMainWindow are not shown


In a simple application, in which a user types some text in QLineEdit widget, and the text is to be shown in a QLabel.

When compiling the application, I get no errors. However, QLabel and QLineEdit widgets are not visible when the window is opened.

Window.h

#ifndef WINDOW_H
#define WINDOW_H

#include <QMainWindow>

class QGridLayout;
class QLabel;
class QLineEdit;

class Window : public QMainWindow
{
    Q_OBJECT

public:
    explicit Window(QWidget *parent = 0);

private:
    QGridLayout *mainLayout;
    QLabel *label;
    QLineEdit *lineEdit;
};

#endif // WINDOW_H

Window.cpp

#include "Window.h"
#include <QGridLayout>
#include <QLineEdit>
#include <QLabel>

Window::Window(QWidget *parent)
    : QMainWindow(parent)
{
    mainLayout = new QGridLayout;
    label = new QLabel(tr("Text"));
    lineEdit = new QLineEdit;

    mainLayout->addWidget(label, 0, 0);
    mainLayout->addWidget(lineEdit, 1, 0);
    setLayout(mainLayout);

    connect(lineEdit, SIGNAL(textChanged(QString)),
            label, SLOT(setText(QString)));
}

main.cpp

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

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

    Window window;
    window.show();

    return app.exec();
}

I couldn't find any mistake in the code.


Solution

  • A QMainWindow must have a central widget, even if it's just a placeholder. Also note that it has its own layout for adding toolbars, menubars, etc. - so you probably want to set the layout (mainLayout in your code) for the central widget instead.

    Check the QMainWindow class reference for details.

    To make your widgets visible in the main window, you could modify your constructor like this:

    Window.cpp

    #include "Window.h"
    #include <QGridLayout>
    #include <QLineEdit>
    #include <QLabel>
    
    Window::Window(QWidget *parent)
        : QMainWindow(parent)
    {
        QWidget* someWidget = new QWidget(this);
        mainLayout = new QGridLayout;
        label = new QLabel(tr("Text"));
        lineEdit = new QLineEdit;
    
        mainLayout->addWidget(label, 0, 0);
        mainLayout->addWidget(lineEdit, 1, 0);
        someWidget->setLayout(mainLayout);
    
        connect(lineEdit, SIGNAL(textChanged(QString)),
                 label, SLOT(setText(QString)));
    
        setCentralWidget(someWidget);
    }