我试图在另一个小部件(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/