Search code examples
qtqtableviewqfilesystemmodelqitemdelegate

How to set text color QTableView with QFileSystemModel in Qt?


I use Qtableview to show file and folder (only show icon, filename, size). I want to paint text color(all text in row) for a few specific files.

Eg: file starts with 'ABC' is gray; 'XYZ' is red,...


Solution

  • Best practice is to use QIdentityProxyModel and override a data method for necessary roles. For example:

    QVariant MyProxy::data(const QModelIndex &index, int role) const
    {
      // Whatever you want in condition:
      if ( sourceModel()->data(index, Qt::TextRole).toString() == "SomeFile.txt" )
        switch( role )
        {
        case Qt::ForegroundRole: return Qt::Red;
        case Qt::BackgroundRole: return Qt::Blue; // or any brush, etc
        default:
          break;
        }
    
      return sourceModel()->data(role);
    }
    
    //...
    MyProxy proxy = new MyProxy{};
    proxy->setSourceModel( yourModel );
    view->setModel( proxy );