I have a QTableWidget with some rows.
In each row, one of the cells has another widget set via setCellWidget.
I would like to style this cellWidget based on whether or not the row is selected. For reference, the cellWidget is another QTableWidget but it is disabled/not editable and essentially read-only.
I have found the syntax for accessing sub-controls (in particular, accessing the item of the parent QTableWidget) -- namely MainTable::item
https://doc.qt.io/qt-5/stylesheet-reference.html#list-of-sub-controls
I have also found the (more standard) css-syntax for accessing the pseudo-state of the control -- namely MainTable::item:selected
. https://doc.qt.io/qt-5/stylesheet-reference.html#list-of-pseudo-states
If I naively use this to style the selected item (tablerow) as yellow as below
def add_file(self, row, element):
"""populate a new row in the table"""
# self is the parent QTableWidget
self.setRowHeight(row, self.ICON_SIZE.height())
img = self.create_thumbnail(element['filepath'])
# add an image to the first column
item = QTableWidgetItem("",0)
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
item.setData(Qt.DecorationRole, img)
item.setData(Qt.TextAlignmentRole, Qt.AlignHCenter|Qt.AlignCenter)
item.setData(Qt.SizeHintRole, self.ICON_SIZE)
self.setItem(row, self.THUMBCOL, item)
# StatsTable is another nested QTableWidget
stats = StatsTable(element)
# add the new nested table to the outer main tables second column
self.setCellWidget(row, self.STATSCOL, stats)
self.setStyleSheet("""
MainTable::item:selected
{
background: yellow;
color: purple;
}
""")
The entire row except for the cellWidget will have a yellow background.
Now if I modify the QSS-selector in an attempt to access the child widget, I get unexpected results:
MainTable::item:selected QTableWidget
{
background: yellow;
color: purple;
}
this results in every row having its cellWidget-table given a yellow background independent of the selection-status of the row (unlike before where only the selected row sans the nested table had a yellow background).
Is there something simple I am overlooking here, or do I have to create some callbacks to manually apply and unapply the style when a row is selected?
this is a selected row with the first QSS applied
this is a selected row with the second QSS applied
neither of these two has the cellWidget styled if the row is selected.