更改QTableWidget默认选择颜色,并使其半透明

问题描述 投票:0回答:1

我正在尝试更改QTableWidget中的选择的默认颜色,但我需要使其透明,以便我仍然可以看到底层单元格的颜色。

我用了 :

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

所以现在选择颜色有点红色,但有些单元格定义为:

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

并且仍然会通过选择颜色覆盖单元格的颜色(没有混合,只有粉红色选择)。我尝试为单元格而不是背景颜色设置前景色:

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

但它没有改变任何东西。那么有一个简单的方法,或者我应该手工处理选择? (用我自己的颜色重绘所选行)先谢谢。

python pyqt qtablewidget
1个回答
0
投票

我有几乎相同的情况,但我不知道我在单元格中有文本,我想要完全透明的选择(所以没有改变背景颜色)如果你设置透明的颜色,它会是固体(qt中的错误?)所以我设置文本是BOLD(=选中)并在这里转换选择风格的代码,也许会有所帮助

//.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%的项目

选择演示

© www.soinside.com 2019 - 2024. All rights reserved.