QTreeView 在主函数之外不起作用

QTreeView doesn't work outside the main function

我正在尝试在另一个小部件 (QMainWindow) 中生成一个简单的 QTreeView。以下代码按预期工作并显示树视图,

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();
}

但是如果我提取生成树视图的代码,似乎什么也没有发生。提取出来的函数如下:

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();
}

而main函数中对应的函数调用如下:


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

  MainWindow w;
  w.show();

  create_tree(&w);

  return app.exec();
}

提取的函数 create_tree 是如何工作的,为什么不显示树视图?

QFileSystemModel model;

QTreeView tree;

是局部堆栈变量,这意味着一旦退出 create_tree 函数它们就会消失。 您可以通过使用 new 在堆上创建它们来解决您的问题,这将使它们保持活动状态。小心,您需要考虑如何销毁这些创建的 objects。 Qt parenting 系统在那里有很大的帮助,因为 parent 会在它被销毁时销毁它的 children,所以你的树视图很好。您应该为您的模型考虑好的 parent,以确保不会造成内存泄漏。

您的函数的工作版本如下所示 - 请注意您仍然需要处理模型删除:

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();
}