我正在尝试使用QTreeView(使用底层QFileSystemModel)来显示目录树。如果我将RootPath设置为父目录,那么我会看到所有子节点,但不是父节点。如果我将RootPath设置为父节点的父节点,那么我会看到父节目及其所有兄弟节点。有没有办法让它显示没有兄弟姐妹和所有孩子的父母?
由于
答案 0 :(得分:1)
这适用于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();
}
答案 1 :(得分:-1)
QTreeView
说明中的example谈到了调用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();
}