我正在尝试让 QTreeView(使用底层 QFileSystemModel)来显示目录树。如果我将 RootPath 设置为父目录,那么我会看到所有子目录,但看不到父目录。如果我将 RootPath 设置为父目录的父目录,那么我会看到父目录及其所有兄弟目录。有没有办法让它显示没有兄弟姐妹的父母和所有孩子?
谢谢
这适用于我在 Linux 上。我并没有声称它是最好的实现,我不确定使用反斜杠分隔符是否可以在 Windows 上使用。我知道 Qt 将它们转换为本机分隔符,但我不知道它是否是来自模型data
方法的本机分隔符。
#include <QApplication>
#include <QFileSystemModel>
#include <QSortFilterProxyModel>
#include <QTreeView>
class FilterModel : public QSortFilterProxyModel
{
public:
FilterModel( const QString& targetDir ) : dir( targetDir )
{
if ( !dir.endsWith( "/" ) )
{
dir += "/";
}
}
protected:
virtual bool filterAcceptsRow( int source_row
, const QModelIndex & source_parent ) const
{
QString path;
QModelIndex pathIndex = source_parent.child( source_row, 0 );
while ( pathIndex.parent().isValid() )
{
path = sourceModel()->data( pathIndex ).toString() + "/" + path;
pathIndex = pathIndex.parent();
}
// Get the leading "/" on Linux. Drive on Windows?
path = sourceModel()->data( pathIndex ).toString() + path;
// First test matches paths before we've reached the target directory.
// Second test matches paths after we've passed the target directory.
return dir.startsWith( path ) || path.startsWith( dir );
}
private:
QString dir;
};
int main( int argc, char** argv )
{
QApplication app( argc, argv );
const QString dir( "/home" );
const QString targetDir( dir + "/sample" );
QFileSystemModel*const model = new QFileSystemModel;
model->setRootPath( targetDir );
FilterModel*const filter = new FilterModel( targetDir );
filter->setSourceModel( model );
QTreeView*const tree = new QTreeView();
tree->setModel( filter );
tree->setRootIndex( filter->mapFromSource( model->index( dir ) ) );
tree->show();
return app.exec();
}
描述中的示例QTreeView
谈论调用QFileSystemModel::setRootPath
但描述QFileSystemModel
谈论使用QTreeView::setRootIndex
。文件说:
可以通过设置树视图的根索引来显示特定目录的内容
这是一个对我有用的例子。在这个例子中,当我不打电话时tree->setRootIndex(model->index((dir)))
,它曾经向我显示所有目录的列表,而不是c:/sample
。希望这可以帮助。
#include <QtGui/QApplication>
#include <QtGui>
#include <QFileSystemModel>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFileSystemModel *model = new QFileSystemModel;
QString dir("c:/sample");
model->setRootPath(dir);
QTreeView *tree = new QTreeView();
tree->setModel(model);
tree->setRootIndex(model->index((dir)));
tree->show();
return a.exec();
}