gartenriese
gartenriese

Reputation: 4356

Can't open Widget from the MainWindow

I want to open a Widget from my MainWindow. I thought this was easy to do, and all the tutorials I read do it like this:

void MainWindow::on_pushButton_Types_clicked()
{
    m_typesWin = new TypesWindow(m_db, this);
    m_typesWin->show();
    this->hide();
}

However, this only works for me if I don't pass "this" into the constructor. When I add "this" to the constructor, I don't see the widget, the program just stops. If I don't hide "this", then I can see that parts of my widget are actually in my main window. I have no idea why.

EDIT: The classes are automatically created by QtCreator, so they should be alright.

Upvotes: 0

Views: 411

Answers (2)

Brandon Jipiu
Brandon Jipiu

Reputation: 1

To open a Mainwindows from the new Qwidget:

1)in the NEWWIDGET.CPP:

QWidget *w;

NEWWIDGET::NEWWIDGET(QWidget *parent,QWidget *win) :
  QWidget(parent),
  ui(new Ui::NEWWIDGET)
{
  ui->setupUi(this);
  w=win;
}

..

void NEWWIDGET::on_pushButton_clicked()
{
  this->hide();
  w->show();
}

2)In the NEWWIDGET.H

public:
    explicit NEWWIDGET(QWidget *parent=nullptr,QWidget *win=nullptr);
    ~NEWWIDGET();

Upvotes: 0

Lahiru Chandima
Lahiru Chandima

Reputation: 24068

If you want a QWidget to be displayed as a window, a parent widget should not be specified to that widget. Here, because you specify main window as the parent of TypesWindow, TypesWindow becomes embedded in main window. So when you hide main window, TypesWindow embedded in main window also gets hidden.

Since you want TypesWindow to be a separate window, don't pass parent widget to the QWidget constructor in TypesWindow constructor. If you want to access main window from TypesWindow, you can store main window pointer in a pointer field in TypesWindow.

Upvotes: 1

Related Questions