How do I display different background colors based on the content?
Refer to ECMWF Metview source code implementation.
QT's model in which different types of data are differentiated by role, QT's macro itemdatarole provides some roles:
1234567891011121314151617181920212223242526272829303132 |
enum itemdatarole { displayrole = 0, decorationrole = 1, editrole = 2, tooltiprole = 3, statustiprole = 4, whatsthisrole = 5, //Metadata fontrole = 6, textalignmentrole = 7, backgroundcolorrole = 8, backgroundrole = 8, textcolorrole = 9, foregroundrole = 9, checkstaterole = ten, //Accessibility accessibletextrole = one , accessibledescriptionrole = . // more general purpose sizehintrole = , initialsortorderrole = + , //Internal uilib roles. Start worrying when public roles go. displaypropertyrole = , decorationpropertyrole = - tooltippropertyrole = , statustippropertyrole = whatsthispropertyrole = - //Reserved userrole = }; |
You can also customize the role, as long as the value is greater than userrole.
123456 |
enum imagenavigtionmodelrole{ cachedimagerole = Qt::userrole + , imagemetadatarole = Qt::userrole + }; |
The QT model uses the data function, the SetData function, to get and set the specific values of the various roles. When we need to modify the background color, we can modify the return data of the Backgroundcolorrole role:
C + +
12345678910111213141516171819202122 |
qvariant imagenavigationmodel::data(const qmodelindex &index, int role) const { if(role = = Qt::backgroundrole) { QStandardItem< Span class= "Crayon-o" >* node = itemfromindex ( Span class= "crayon-v" >index. Sibling (index. Row () ,0) ; //each row is the same color qvariant cached_image_role = node-to-data (cachedimagerole) ; if(! Cached_image_role. IsNull()) { if(index. Row()%2 = = 0) return qcolor("#FFE6BF"); Else return qcolor("#FFF2DE"); } Else { return qstandarditemmodel::data(index, role); } } return qstandarditemmodel::data(index, role); } |
This allows you to customize the background color of your data.
Set the background color of an item in Qstandarditemmodel