Programmatically change the background color of a QModelIndex role



  • My application contains a QTreeView that displays a custom QSortFilterProxyModel class using a QFileSystemModel as its source. I want to programmatically change the background color of the QModelIndex I am working with (basically yellow, green, and red indicating in progress, pass, fail for the file I am processing). How can I programmatically change the background color for selected index of Treeview control? Keep in mind that the current view has a alternating color scheme that I would like to keep just in case I have not dealt with the file yet.



  • The standard method is to override the data method in your model and return the required color for the BackgroundRole

    @QVariant MyModel::data ( const QModelIndex & item, int role ) const
    {
    //change the background color
    if (role == Qt::BackgroundRole)
    {
    return QColor(255, 0, 0);
    }

    return QSortFilterProxyModel::data(item, role);
    }@



  • Thanks Noah.. However, how can I preserve the alternating row color for files (rows) I have processed?



  • If you don't want to set the color for a specific row just fall through to the default. You'll have do something a bit more complicated than my code to determine the appropriate color, obviously.

    @QVariant MyModel::data ( const QModelIndex & item, int role ) const
    {
    //change the background color
    if (role == Qt::BackgroundRole)
    {
    if (item.data() = "In Progress")
    return QColor(255, 255, 0); //yellow
    else if (item.data() = "Fail")
    return QColor(255, 0, 0); //red
    else if (item.data() = "Pass")
    return QColor(0, 255, 0); //green
    //else fall through to the default alternating background color
    }

    return QSortFilterProxyModel::data(item, role);
    }@



  • it works! thanks Noah!



  • Thank you for your answers on this question. I found this topic and it has been very helpful. Would you be able to provide your code that calls this function to change the background color?

    Thanks!


  • Qt Champions 2016

    @StephanB
    hi and welcome
    The thread is 4 years old so the persons are most likely never to see it.

    The rest of the code belong to a custom/subclass model.
    So what call the code, it the framework / the view that use this model.

    You can read about it here:
    http://doc.qt.io/qt-5/model-view-programming.html
    https://www.youtube.com/watch?v=ytKDsJgJa4k
    http://www.informit.com/articles/article.aspx?p=1405547&seqNum=3


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.