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_())
One selection works good.
Multiple selection just applies the color to all items selected. I want the left one to be red once selected.
color_list
defined inmain
. When column=i, the selection color of it should becolor_list[i]
. – user6456568