QTreeView在主函数之外无法工作。

问题描述 投票:0回答:1

我试图在另一个widget(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();
}

而主函数中对应的函数调用如下


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

  MainWindow w;
  w.show();

  create_tree(&w);

  return app.exec();
}

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

c++ qt5 qtreeview
1个回答
1
投票
QFileSystemModel model;

QTreeView tree;

是本地堆栈变量,这意味着一旦你退出了 create_tree 你可以通过使用new在堆上创建对象来解决你的问题,这将使它们保持活力。要注意的是,你需要考虑如何销毁这些创建的对象。Qt的父系统在这方面有很大的帮助,因为父系统会在它的子系统被销毁时销毁它的子系统,所以你的树形视图是很好的。你应该考虑好你的模型的父体,以确保你创建的模型没有内存泄漏。

你的函数的工作版本看起来像这样--小心你仍然需要处理模型的删除。

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.