Change QTableWidget default selection color, and m

2019-09-16 08:45发布

问题:

I am trying to change the default color for selection in a QTableWidget, but I need to make it transparent so that I can still see the color of the underlying cell.

I used :

self.setStyleSheet("QTableView{ selection-background-color: rgba(255, 0, 0, 50);  }")
self.setSelectionBehavior(QAbstractItemView.SelectRows)

So now the selection color is kind of red, but some cells are defined as:

cell.setBackgroundColor(color)
...
self.setItem(i, j, cell)

And still the color of the cell is overwritten by the selection color (no mixing, just the pink-red selection). I tried setting a foreground color for the cells instead of background color :

brush = QBrush(color, Qt.SolidPattern)
cell.setForeground(brush)

but it does not change anything. So is there a simple way to do it, or should I handle the selection by hand ? (redraw the selected row with my own colors) Thanks in advance.

回答1:

I had almost same scenario, but insetead i have text in cells and i wanted fully-transparent selection (so no change to background color) if you set transparent color, it will be solid (bug in qt?) so i set text to be BOLD (= selected) and turn of selection-style here the code, maybe it would help

//.h
#include <QStyledItemDelegate>
class SelectionControlDelegate : public QStyledItemDelegate
{
    public:
        SelectionControlDelegate(QObject* parent = 0);
        void initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const override;
};

//.cpp
SelectionControlDelegate::SelectionControlDelegate(QObject* parent) : QStyledItemDelegate(parent)
{
}

void SelectionControlDelegate::initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const
{
    QStyledItemDelegate::initStyleOption(option, index);
    const bool selected = option->state & QStyle::State_Selected;
    option->font.setBold(selected); // this will represent selected state
    if (selected)
    {
        option->state = option->state & ~QStyle::State_Selected; // this will block selection-style = no highlight
    }
}

// in widget class
...
_ui->tableView->setItemDelegate(new SelectionControlDelegate(this));
...


// when setting cell background, i would change also text color 
QColor textColor = backgroundColor.value() <= 120 ? Qt::white : Qt::black;  // if it is dark, text would be white otherwise black
// or you can compute invert color... 

here is my visualization: 5% and 25% items are selected

selection presentation