Qt的absoluteFilePath()方法返回错误路径

1 投票
1 回答
790 浏览
提问于 2025-04-16 16:19

我正在尝试用以下几个函数来打印在树形视图中指向的文件路径:

1) 为树形视图设置根索引:

self.treeView.setRootIndex(self.model.setRootPath("/some/unix/catalog"))

2) 设置点击文件和打印文件名的函数之间的连接:

QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL("clicked(QModelIndex)"), self.print_path)

3) 在 print_path 函数中打印,这个函数接受一个 (QModelIndex) 索引作为参数:

print QtCore.QFileInfo(index.data(0).toString()).absoluteFilePath()

我的问题是,我得到的是:

/path/to/source/files/of/the/project/nameofthefile.extension

而不是:

/path/to/pointed/file/nameofthefile.extension

即使指向的文件在子目录中,这些函数也只返回文件名和扩展名,连接到源文件的路径上。我哪里做错了?

1 个回答

2

QtCore.QFileInfo(index.data(0).toString())

这段代码中,你只是用本地路径创建了一个新的 FileInfo 实例。这个 FileInfo 对象并不知道这个文件名在哪个文件夹里,所以它会使用默认的文件夹。可以把它想象成

QtCore.QFileInfo("readme.txt")

那么,FileInfo 怎么知道你说的 readme.txt 是在 /my/nice/files/ 文件夹里呢?

你应该从

QFileSystemModel::fileInfo

获取 FileInfo。

所以在你的情况下:

self.model.fileInfo(index).absoluteFilePath()

撰写回答