简体   繁体   中英

QTreeView doesn't work outside the main function

I'm trying to generate a simple QTreeView inside another widget (QMainWindow). The following code works as expected and displays the tree-view,

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);

  MainWindow w;
  w.show();

  QString rootPath = "C:/";

  QFileSystemModel model;
  model.setRootPath("");

  QTreeView tree;
  tree.setModel(&model);
  if (!rootPath.isEmpty()) {
    const QModelIndex rootIndex = model.index(QDir::cleanPath(rootPath));
    if (rootIndex.isValid())
      tree.setRootIndex(rootIndex);
  }

  tree.setParent(&w);
  tree.show();

  return app.exec();
}

but if I extract the code that generates the tree-view, nothing seems to happen. The extracted function is as follows:

void create_tree(QMainWindow *w) {
  QString rootPath = "C:/";

  QFileSystemModel model;
  model.setRootPath("");

  QTreeView tree;
  tree.setModel(&model);
  if (!rootPath.isEmpty()) {
    const QModelIndex rootIndex = model.index(QDir::cleanPath(rootPath));
    if (rootIndex.isValid())
      tree.setRootIndex(rootIndex);
  }

  tree.setParent(w);
  tree.show();
}

and the corresponding function call in main function is as follows:


int main(int argc, char *argv[]) {
  QApplication app(argc, argv);

  MainWindow w;
  w.show();

  create_tree(&w);

  return app.exec();
}

How does the extracted function create_tree work and why is it not showing the tree view?

QFileSystemModel model;

and

QTreeView tree;

Are local stack variables, meaning they will be gone once you exit the create_tree function. You can solve your issue by creating them on the heap by using new, which will keep them alive. Be careful, that you need to think about how you destroy these created objects. The Qt parenting system is a great help there, because the parent will destroy its children when it is destroyed, so your tree view is fine. You should think about good parent for your model to make sure you create no memory leak.

A working version of your function looks like this - be careful that you still need to handle the models deletion:

void create_tree(QMainWindow *w) {
  QString rootPath = "C:/";

  QFileSystemModel* model = new QFileSystemModel();
  model->setRootPath("");

  QTreeView* tree = new QTreeView();
  tree->setModel(model);
  if (!rootPath.isEmpty()) {
    const QModelIndex rootIndex = model->index(QDir::cleanPath(rootPath));
    if (rootIndex.isValid())
      tree->setRootIndex(rootIndex);
  }

  tree->setParent(w);
  tree->show();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM