jdl
jdl

Reputation: 6323

QGraphicsView not displaying in mainWindow

If I just start from main with a QGraphicsView, it displays. But if I place the QGraphicView in mainwindow.cpp, it flashes up and disappears??


 int main(int argc, char **argv)
 {
     QApplication a(argc, argv);

     QGraphicsView view;
     view.resize(1000, 800);
     view.show();

     return a.exec();
 }

 int main(int argc, char **argv)
 {
     QApplication a(argc, argv);

     MainWindow w;
     w.show();

     return a.exec();
 }


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

    QPushButton *m_button1 = new QPushButton("1", this);
    m_button1->setGeometry(QRect(QPoint(100, 100), QSize(100, 100)));
    connect(m_button1, SIGNAL(released()), this, SLOT(handleButton1()));
}

void MainWindow::handleButton1()
{
    QGraphicsView view;
    view.resize(1000, 800);
    view.show();
}

Upvotes: 1

Views: 4024

Answers (1)

Muckle_ewe
Muckle_ewe

Reputation: 1123

You've created a local QGraphicsView variable there in the handleButton1() function that will be destroyed as soon as the function finishes, in your first example, the view would exist until the end of main() which is the end of the application, i.e it exists until you close the application. Your best bet would be to either use Qt Designer to place the QGraphicsView in the MainWindow or to give MainWindow a private QGraphicsView* member variable

If you use a private variable, use Qts built in memory management to set the parent of it to the MainWindow so it's cleaned up when the window is destroyed.

class MainWindow : QMainWindow {
    // etc...
    private:
        QGraphicsView *view;
}

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

    view = new QGraphicsView(this);
    view->setGeometry(QRect(50, 50, 400, 200));
    view->show();

    // etc...
}

Instead of using 'this' as above, if you have a central widget, or any widget where you want the QGraphicsView, you would do

view = new QGraphicsView(ui->centralWidget);

Upvotes: 3

Related Questions