PyQt4中的选择突出显示QTableWidget以完整块颜色填充所选单元格的背景

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

我正在研究一个小型PyQt4任务管理器。类似的问题在这里问Change QTableWidget default selection color, and make it semi transparent。从这篇文章中,我尝试setStyleSheet选择背景颜色不透明度,但突出显示仍然覆盖单元格背景颜色。是否有人可以帮我展示如何将其更改为边框颜色?

下图是我目前的结果

enter image description here

这是我愿意实现的,正如您所看到的,高光选择只是覆盖背景颜色,但不能覆盖它。

enter image description here

最后,希望我的问题对每个人都足够清楚,如果发现任何不清楚或错误,请告诉我,我会尽快修复!谢谢!

python python-2.7 pyqt pyqt4 qtablewidget
1个回答
0
投票

改变颜色的一种方法是使用委托。

为此我们必须得到当前的背景颜色,获得背景颜色的任务是繁琐的,因为QTableWidget有自己的颜色作为背景,它也有你添加到QTableWidgets和其他类型的元素的颜色所以我的答案目前有有限的支持但这个想法是可扩展的。

要显示为所选元素背景的颜色是背景颜色的平均值和正确选择的颜色,在这种情况下我们选择颜色#cbedff

我在以下类中实现了以上所有内容:

class TableWidget(QTableWidget):
    def __init__(self, *args, **kwargs):
        QTableWidget.__init__(self, *args, **kwargs)

        class StyleDelegateForQTableWidget(QStyledItemDelegate):
            color_default = QColor("#aaedff")

            def paint(self, painter, option, index):
                if option.state & QStyle.State_Selected:
                    option.palette.setColor(QPalette.HighlightedText, Qt.black)
                    color = self.combineColors(self.color_default, self.background(option, index))
                    option.palette.setColor(QPalette.Highlight, color)
                QStyledItemDelegate.paint(self, painter, option, index)

            def background(self, option, index):
                item = self.parent().itemFromIndex(index)
                if item:
                    if item.background() != QBrush():
                        return item.background().color()
                if self.parent().alternatingRowColors():
                    if index.row() % 2 == 1:
                        return option.palette.color(QPalette.AlternateBase)
                return option.palette.color(QPalette.Base)

            @staticmethod
            def combineColors(c1, c2):
                c3 = QColor()
                c3.setRed((c1.red() + c2.red()) / 2)
                c3.setGreen((c1.green() + c2.green()) / 2)
                c3.setBlue((c1.blue() + c2.blue()) / 2)

                return c3

        self.setItemDelegate(StyleDelegateForQTableWidget(self))

例:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = TableWidget()
    w.setColumnCount(10)
    w.setRowCount(10)
    for i in range(w.rowCount()):
        for j in range(w.columnCount()):
            w.setItem(i, j, QTableWidgetItem("{}".format(i * j)))
            if i < 8 and j < 8:
                color = QColor(qrand() % 256, qrand() % 256, qrand() % 256)
                w.item(i, j).setBackground(color)
    w.show()
    sys.exit(app.exec_())

取消:

enter image description here

选择:

enter image description here

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