2
votes

I'd like to have different selection color when an item is selected. But the QTableWidget::item:selected{ background-color: } only works when there is only one item selected, otherwise all selected items will have the same selection color. So is there a way to make every item have individual selection color?

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.MainWindow=MainWindow
        self.MainWindow.resize(300, 100)
        self.centralwidget = QtWidgets.QWidget(self.MainWindow)
        self.MainWindow.setCentralWidget(self.centralwidget)
        """table """
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.insertRow(0)
        self.tableWidget.setColumnCount(2)
        
        self.tableWidget.setItem(0,0,QtWidgets.QTableWidgetItem("red"))
        self.tableWidget.setItem(0,1,QtWidgets.QTableWidgetItem("blue"))
        self.tableWidget.itemSelectionChanged.connect(self.ChangeSelectionColor)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
    def ChangeSelectionColor(self):
        try:
            for item in self.tableWidget.selectedItems():
                col=item.column()
            self.tableWidget.setStyleSheet("QTableWidget::item:selected{ background-color: %s }"%color_list[col])
        except UnboundLocalError:
            pass
if __name__ == "__main__":
    import sys
    color_list=['red','blue']
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

enter image description here

enter image description here

One selection works good.

enter image description here

Multiple selection just applies the color to all items selected. I want the left one to be red once selected.

1
On what does the color depend?eyllanesc
@eyllanesc the color_list defined in main. When column=i, the selection color of it should be color_list[i] .user6456568
I think you have not understood my question, I say you have a table of 2 rows and 3 columns, what would be the colors, what should each cell have when it is selected?eyllanesc
@eyllanesc The question I posted is just a simplification. In my project, every item's color is stored in a list as well.user6456568
I want to place a solid answer, let's say the list is of length 5 and 6 items are selected, what color should the sixth item have?eyllanesc

1 Answers

4
votes

Use qss in this case is not appropriate because they have many limitations, it is appropriate to implement a delegate, in this case a class that inherits from QStyledItemDelegate. But before that we must save the color information through the setData method of QTableWidgetItem:

it = QTableWidgetItem("some_text")
it.setData(Qt.UserRole, some_color)

Then the paint method of QStyledItemDelegate is overwritten and the selection color is changed:

class ColorDelegate(QStyledItemDelegate):
    def paint(self, painter, option, index):
        color = index.data(Qt.UserRole)
        option.palette.setColor(QPalette.Highlight, color)
        QStyledItemDelegate.paint(self, painter, option, index)

Then the delegate is established:

your_qtablewidget.setItemDelegate(ColorDelegate())

A complete example I show it below:

from PyQt5.QtWidgets import QApplication, QStyledItemDelegate, QTableWidget, QTableWidgetItem, QStyle
from PyQt5.QtGui import QColor, QPalette
from PyQt5.QtCore import qrand, Qt

class ColorDelegate(QStyledItemDelegate):
    def paint(self, painter, option, index):
        color = index.data(Qt.UserRole)
        option.palette.setColor(QPalette.Highlight, color)
        QStyledItemDelegate.paint(self, painter, option, index)


def fun(n_rows, n_columns):
    return [[QColor(qrand() % 256, qrand() % 256, qrand() % 256) for i in range(n_rows)] for j in range(n_columns)]

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    n_rows, n_columns = 10, 10
    colors = fun(n_rows, n_columns)
    w = QTableWidget()
    w.setColumnCount(n_columns)
    w.setRowCount(n_columns)
    for i in range(w.rowCount()):
        for j in range(w.columnCount()):
            it = QTableWidgetItem("{}-{}".format(i, j))
            it.setData(Qt.UserRole, colors[i][j])
            w.setItem(i, j, it)
    w.setItemDelegate(ColorDelegate())
    w.show()
    sys.exit(app.exec_())