c++ - QTreeView在主要功能之外不起作用

标签 c++ qt5 qtreeview

我试图在另一个小部件(QMainWindow)中生成一个简单的QTreeView。以下代码可以正常工作并显示树形 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();
}

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

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如何工作,为什么不显示树形 View ?

最佳答案

QFileSystemModel model;


QTreeView tree;

是局部堆栈变量,这意味着一旦退出create_tree函数,它们就会消失。
您可以通过使用new在堆上创建它们来解决问题,这将使它们保持 Activity 状态。请注意,您需要考虑如何销毁这些创建的对象。 Qt育儿系统在那里提供了很大的帮助,因为当 parent 被销毁时, parent 将销毁它的 child ,因此您的树形 View 很好。您应该为模型考虑好父级,以确保不会造成内存泄漏。

您的函数的工作版本如下所示-注意,仍然需要处理模型删除:
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();
}

关于c++ - QTreeView在主要功能之外不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62258744/

相关文章:

c++ - OpenCV,均衡图像轮廓直方图

c++ - 在 QTreeview 特定单元格中添加 QCombobox

c++ - 如何将行号添加到 QTreeView?

c++ - 在 Qtreeview 中从 parent 那里得到 child

c++ - mpirun 不工作并要求将 TMPDIR 变量更改为/tmp

c++ - 编译ros节点时对...的 undefined reference

qt - 从QWebEngineView或QWebEnginePage删除ScrollBar

c++ - 从文件动态更新 Qdialog 中的 QTextBrowser(由另一个作业更新)

c++ - 使用 istream_iterator 和 istream 重载读取到文件末尾

c++ - Qt 5 中的屏幕键盘