It's utterly impossible to change this behavior with the standard style in Qt. You need to implement your own specific style in order to work around this.
Change color highlight of icons in QTableView, when the cell is selected
-
20-09-2022 - |
Pregunta
When a cell is selected in QTableView, the icons in it are given a blue highlight, how can I control the color of this highlight or disable it?
I tried setting the QPalette::Highlight but it didn't work.
Edit:
Okay, so I do know how to change the background color and text color and color highlight, but not for an icon. If I return an icon as decoration for a cell, it is given a light blue highlight when the cell is selected. How do I remove this?
Solución 3
Otros consejos
You can use style sheets to define the color of your elements. The name of the selected item in your QTableView
is selection-background-color
. So, changing the color of this element you will chose the background color that your prefer.
#include <QtWidgets/QApplication>
#include <QtWidgets/QTableView>
#include <QStandardItemModel>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
QTableView *table = new QTableView();
QStandardItemModel *model = new QStandardItemModel(2,2);
table->setModel(model);
table->setStyleSheet("selection-background-color: red");
table->show();
return app.exec();
}
Look how it looks in the picture:
I discovered a way around this issue, but it has some cost associated with it.
Fundamentally, deep within Qt code it is calling onto QIcon::paint()
and passing QIcon::Selected
as the icon mode, so the issue is that the "selected" form of the icon's pixmap at the desired resolution is the one auto-generated by Qt.
I worked around this by setting the Selected
form of the icon to be the same as the Normal
mode:
// Make the "Selected" version of the icon look the same as "Normal".
for (const auto& size : icon.availableSizes())
{
icon.addPixmap(icon.pixmap(size, QIcon::Normal, QIcon::Off),
QIcon::Selected, QIcon::Off);
icon.addPixmap(icon.pixmap(size, QIcon::Normal, QIcon::On),
QIcon::Selected, QIcon::On);
}
The downside is extra time spent doing this, possibly extra memory to store it, and wasted time generating the selected icons that we're throwing away.
In my case I'm using a QStyledItemDelegate
and unfortunately that doesn't give you the ability to more closely influencing how the icon is rendered without completely reimplementing how QStyle::CE_ItemViewItem
is rendered in your style.
Come to think of it, if you use a proxy style it wouldn't be too hard to override how CE_ItemViewItem
is rendered to not use a selected icon, so that would be an option too.