I have a QListWidget in PySide2 and I would like different colors for the selected items. Is this possible? I will include 2 pictures to demonstrate.
And this is what I would like to have:
You have to use a delegate and override the QPalette of the QStyleOptionViewItem. In the following example, the highlight color depends on whether it is an even row or not.
from PySide2 import QtCore, QtGui, QtWidgets
import random
class HighlightedDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(HighlightedDelegate, self).initStyleOption(option, index)
# highlight color
color = (
QtGui.QColor("gray")
if index.row() % 2 == 0
else QtGui.QColor("salmon")
)
option.palette.setColor(
QtGui.QPalette.Normal, QtGui.QPalette.Highlight, color
)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QListWidget(
selectionMode=QtWidgets.QAbstractItemView.MultiSelection
)
delegate = HighlightedDelegate(w)
w.setItemDelegate(delegate)
for i in range(100):
it = QtWidgets.QListWidgetItem("item-{}".format(i))
w.addItem(it)
w.resize(640, 480)
w.show()
sys.exit(app.exec_())