My QT application is opening two windows. One empty and one with the button1 showing. Could someone tell me why?
I've tried everything, but I can't find the source of the problem. If anyone can help me.
main.cpp
#include <QtWidgets>
#include "./mainwindow.h"
int main(int argc, char **argv)
{
QApplication app (argc, argv);
MainWindow myWindow;
myWindow.show();
return app.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStackedWidget>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include <QtWidgets>
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
{
QWidget *page1 = new QWidget();
QWidget *page2 = new QWidget();
QGridLayout *layout = new QGridLayout();
QGridLayout *layout1 = new QGridLayout();
QPushButton *button = new QPushButton("Página 1", page1);
QPushButton *button1 = new QPushButton("Página 2", page2);
button->show();
button1->show();
layout->addWidget(button, 0, 0);
layout1->addWidget(button1, 0, 0);
page1->setLayout(layout);
page2->setLayout(layout1);
layout->setColumnMinimumWidth(0, 30);
QStackedWidget *mainContainer = new QStackedWidget(parent);
mainContainer->addWidget(page1);
mainContainer->addWidget(page2);
mainContainer->setCurrentIndex(1);
}
I think it comes from this line:
You should give
this
instead ofparent
for the QStackedWidget, because the parent of your MainWindow is null, and you probably want your StackWidget to be included in your MainWindow I guess.Also, you should probably set your main container as the central widget of the main window. Something like this should work: