繁体   English   中英

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

[英]Selection highlight in PyQt4 QTableWidget fill selected cell's background with full block color

我正在研究小型PyQt4任务管理器。 在这里提出类似的问题更改QTableWidget默认选择颜色,并将其设置为半透明 从这篇文章中,我尝试设置setStyleSheet来选择背景颜色不透明度,但是突出显示仍然覆盖单元格背景颜色。 有没有人可以帮助我展示如何将其更改为边框颜色?

下图是我当前的结果

在此处输入图片说明

如您所见,这就是我愿意达到的目标,高光选择只是覆盖背景颜色,而不是覆盖它。

在此处输入图片说明

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

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

为此,我们必须获取当前的背景颜色,因为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_())

取消选择:

在此处输入图片说明

已选:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM