Antonio Del Sannio
Antonio Del Sannio

Reputation: 315

Show new frame with qt c++

I need to open a new QMainWindow when i click on a button.I would understand why it works with a pointer and does not work with a reference :

the slot that fires a new window is the following ,it should open two window but only the window created with the new operator shows up:

MyWin win1(this);
win1.show();
MyWin *win2 = new MyWin(this);
win2->show();

the following are MyWin.h and MyWin.ccp

#ifndef MyWin_H
#define MyWin_H
#include <QMainWindow>

namespace Ui {
class FrmManipolo1;
}


Class MyWin : public QMainWindow
Q_OBJECT

public:
    explicit MyWin(QMainWindow *parent = 0);
    ~MyWin();

    private:
    Ui::MyWin *ui;
};

#endif

MyWin.cpp

include "MyWin.h"
include "ui_MyWin.h"

MyWin::MyWin(QMainWindow *parent) :
QMainWindow(parent),
ui(new Ui::MyWin)
{
    ui->setupUi(this);
}

MyWin::~MyWin()
{
    delete ui;
}

Upvotes: 1

Views: 420

Answers (1)

Zlatomir
Zlatomir

Reputation: 7034

This doesn't work:

MyWin win1(this);
win1.show();

because it creates the win1 object on the stack, so the win1 object is destroyed at the end of the current scope, before it can actually be drawn.

This works:

MyWin *win2 = new MyWin(this);
win2->show();

because the object is allocated on the heap and it's lifetime doesn't end at the current scope, it ends when you call delete on it's address (the win2 pointer, that only holds the address of the object, not the actual object), or the parent will call delete in your case (because you pass the this pointer as a parent parameter to the constructor).

Upvotes: 3

Related Questions