PDA

View Full Version : QFileSystemModel and QTreeView adding "Path" Column



Jarrod
8th August 2016, 20:21
Hi All,

I am currently writing a program that displays all the directories on my PC, I am using the QFileSystemModel and a QTreeView to display the contents.
The program is working great, however I would like to add a "Path" column to display the path of each folder/File, does an option like this even exist?
Currently the columns are "Name", "Size", "Type", "Date Modified".

Any help would be greatly appreciated.

Thanks.

d_stranz
8th August 2016, 23:01
QFileSystemModel has three additional "user roles" to retrieve the file name, path, and permissions. I guess that when you use an "off the shelf" QFileSystemModel, it will give a column count of 4 and serve up the fields you are seeing.

Others may know of a better way, but my implementation would be to derive from QFileSystemModel and modify the columnCount(), headerData(), and data() methods to add the extra column. In the data method, when asked for the DisplayRole for the column you have designated as the Path column, the custom model returns this:



int MyFileSystemModel::columnCount( const QModelIndex & index ) const
{
return QFileSystemModel::columnCount( index ) + 1;
}

QVariant MyFileSystemModel::headerData( int section, Qt::Orientation o, int role )
{
if ( o == Qt::Horizontal && section == pathColumn )
{
if ( role == Qt::DisplayRole )
return QVariant( "Path" );
else
return QVariant();
}
else
return QFileSystemModel::headerData( section, o, role );
}

QVariant MyFileSystemModel::data( const QModelIndex & index, int role ) const
{
if ( index.column() == pathColumn ) // your member or static variable denoting the path column number
{
if ( role == Qt::DisplayRole )
return QFileSystemModel::data( index, QFileSystemModel::FilePathRole );
else
return QVariant();
}
else
return QFileSystemModel::data( index, role );
}


(Untested, might require tweaking).

anda_skoa
9th August 2016, 08:30
Others may know of a better way, but my implementation would be to derive from QFileSystemModel and modify the columnCount(), headerData(), and data() methods to add the extra column.

It would theoretically also be possible to use a proxy model to add another column, but I also find the approach of just deriving an extended model way easier.

Cheers,
_