更改 QTableWidget 默认选择颜色,并使其半透明 [英] Change QTableWidget default selection color, and make it semi transparent
问题描述
我正在尝试更改 QTableWidget 中选择的默认颜色,但我需要使其透明,以便我仍然可以看到底层单元格的颜色.
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.
我用过:
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.
推荐答案
我有几乎相同的场景,但在单元格中有文本,我想要完全透明的选择(所以没有改变背景颜色)如果您设置透明颜色,它将是实心的(qt 中的错误?)所以我将文本设置为粗体(= 选中)并切换选择样式这里的代码,也许它会有所帮助
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...
这是我的可视化:选择了 5% 和 25% 的项目
here is my visualization: 5% and 25% items are selected
选择展示
这篇关于更改 QTableWidget 默认选择颜色,并使其半透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!