3

QTreeView (基になる QFileSystemModel を使用) を取得して、ディレクトリ ツリーを表示しようとしています。RootPath を親ディレクトリに設定すると、すべての子が表示されますが、親は表示されません。RootPath を親の親に設定すると、親ディレクトリとそのすべての兄弟が表示されます。兄弟なしで親とすべての子供を表示する方法はありますか?

ありがとう

4

2 に答える 2

1

これは、Linuxで機能します。私はそれが最良の実装であると主張しているわけではなく、バックスラッシュ区切り記号の使用が Windows で機能するかどうかもわかりません。dataQtがそれらをネイティブセパレータに変換することは知っていますが、モデルのメソッドから出てくるのがネイティブセパレータであるかどうかはわかりません。

#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();
}
于 2011-06-28T22:10:31.693 に答える
-1

説明の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();
}
于 2011-06-28T10:51:03.153 に答える