PyQt4中的选择高亮显示QTableWidget使用完整的块颜色填充所选单元格的背景
问题描述:
我正在研究一个小型的PyQt4任务管理器。类似的问题在这里请求Change QTableWidget default selection color, and make it semi transparent。从这篇文章,我尝试setStyleSheet选择背景颜色不透明度,但突出显示仍然覆盖单元格背景颜色。有没有人可以帮助我展示如何将其改变为边框颜色?下面PyQt4中的选择高亮显示QTableWidget使用完整的块颜色填充所选单元格的背景
图片是我目前的结果
这是我愿意达到的,因为你看,突出selectionis只是覆盖的背景颜色,但不会忽略它。
最后,希望我的问题是每个人都十分清楚,如果发现任何不清楚或错误,请您让我知道,我会以最快的速度解决越好! 谢谢!
答
更改颜色的一种方法是使用委托。
为此,我们必须获取当前的背景颜色,由于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_())
放弃了:
选择:
我建议提高你的问题,链接是参考和辅助,描述你想要的东西,并把你已经尝试了什么。 – eyllanesc
我的问题已更新,谢谢您的建议! – Coleone
你工作了吗? – eyllanesc