Reputation: 263
I am designing a QTableWidget element in which I need to change the default behavior of a cell when it is edited.
What I need to achieve is that the background of the cell does not change to white, but rather that I can change that background to another color
This is my style sheet code
QTableWidget{
border:none;
border-left:1px solid #b0b9cf;
border-bottom: 1px solid #b0b9cf;
border-right:1px solid #b0b9cf;
selection-color:red;
selection-background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0, 0, 0, 0), stop:1 rgba(255, 255, 255, 0));
}
QHeaderView::section:horizontal{
background:#3d4454;
color:white;
border:0px;
border-bottom:2px solid #b0b9cf;
boder-left: 1px solid #b0b9cf;
border-right:1px solid #b0b9cf;
}
QTableWidget::item:selected{
border:1px solid blue;
}
QTableWidget::item:alternate{
background:red;
color:white;
}
The section indicated in the image represents the cell that is in text editing mode and changes its background color to white. The result that I expect to obtain is that the background and text color does not change when it enters editing mode
In other words, in this case, keep the red background and the white text color
Thank you and I hope you can help me
Upvotes: 0
Views: 731
Reputation: 48529
It's not possible to do it dynamically.
The problem is that QSS (Qt Style Sheets) completely override the underlying style and drawing of complex widgets and their sub-elements is completely done internally by the (private) QStyleSheetStyle.
Most importantly, the alternate row color is only intended as a visual aid, because it's scope is usability, not data based customization: the alternate color should always be related to the base color, because the text color should be the same and readable in both cases.
While QSS allow such customization, advanced usage is limited.
You could theoretically work around the background by using a custom delegate and set a transparent background for the editor, but this would show the current content of the cell also, so it's not a valid option.
There is no direct and easy way to know the actual background/text color of the cell if it's set by stylesheets. The only solution is to use hardcoded colors and set them for the editor:
class Delegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = super().createEditor(parent, option, index)
if index.row() & 1:
editor.setStyleSheet('''
{} {{ background: red; color: white;}}
'''.format(editor.__class__.__name__))
return editor
# ...
tableWidget.setItemDelegate(Delegate(tableWidget))
Notes:
paint()
function; while this would still need hardcoded colors, they could be accessed dynamically more easily;boder-left
should be border-left
);Upvotes: 1