QTreeView closes immediately

63 views Asked by At

I want to display a QTreeView when the user choses that QAction from the menu of my MainWindow (which is AgendaWindow in my case).

The issue is that when I click on the button to display it, it opens the QTreeView and closes it immediately. I put an infinite loop (while(1<2)) but then all my program is blocked and I couldn't find something equivalent to system("pause").

Here is my function:

void AgendaWindow::display_projects()
{
    QStandardItemModel* model = new QStandardItemModel;
    QStandardItem *parentItem= model->invisibleRootItem();
    for (std::vector<Projet*>::const_iterator it =PM.getInstance().getTab().begin(); it!= PM.getInstance().getTab().end(); it++ )
    {
        // I display a project 

        QStandardItem* item=new QStandardItem(QString((*it)->getTitre()));
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        parentItem->appendRow(item);
        Projet* p = (*it);
        // I display every project's tasks

        for (std::vector<Tache*>::const_iterator itp = p->GetTabProjet().begin(); itp != p->GetTabProjet().end(); itp++)
        {
            QStandardItem* itemp = new QStandardItem((*itp)->getTitre());
            //itemp->setFlags(itemp->flags() & ~Qt::ItemIsEditable);
            item->appendRow(itemp);
        }
    }

    QTreeView *treeView=new QTreeView;
    treeView->setModel(model);
    treeView->show();
    //while(1<2);
}

Thank you!

1

There are 1 answers

1
perencia On

UPDATE: This answer is wrong. The object is on the heap not the stack. There's a potential memory leak though.

The QTreeView you are creating is local to the method. When it goes out of scope (when the method ends) it is destroyed. You need to have the QTreeView maybe as a member of a class and call the show method when convenient.

It seems you lack the basics regarding Qt and GUI. Read about the Qt event loop.