0

I tried to use QTableView in a program. I've already fixed all bugs I got in the model in another testproject I started.

Now, I tried to insert the model and the QTableView in my mainproject, but in contrast to the other project, the QTableView just opens for half a second and then closes immediately! However, the same code was working well in the testproject.

This is my code in the testproject:

#include <QApplication>
#include <QTableView>
#include "start.h"
#include "mymodel.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTableView tableView;
    MyModel myModel(0);
    tableView.setModel(&myModel);
    tableView.setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView.show();
    //Start w;
    //w.show();

    return a.exec();
}

And this is the relevant code in the main project:

void Startseite::on_ButtonOK_clicked()
{
    switch (ui->menuLeiste->currentIndex()) {

    case 0:
    {
        QTableView tableview;
        Model myModel(0);
        tableview.setModel(&myModel);
        tableview.setSelectionBehavior(QAbstractItemView::SelectRows);
        tableview.show();
        break;
    }

    case 1:
    {
        // other functions...
    }
}
}

Model is a QAbstractTableModel.

Does anyone knows, why the TableView closes?

Thanks!

VRTuomi
  • 27
  • 7

1 Answers1

1

You need to create your model and view on the heap, otherwise they will go out of scope at the end of on_ButtonOK_clicked and will be destroyed.

It works in your test project because you create the both in main and they are only destroyed at the end of the program.

Johannes S.
  • 4,566
  • 26
  • 41