Это работает для меня в 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();
}