问题
I have QListWidget in Pyside2 that has icons populating it. I dont like the icons taking on a shaded grey look when the mouse clicks them. Is there a way to disable this action? I will include a picture.
回答1:
You have to use a delegate that disables the QStyle::State_Selected
flag:
from PySide2 import QtCore, QtGui, QtWidgets
class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
option.state &= ~QtWidgets.QStyle.State_Selected
super(StyledItemDelegate, self).initStyleOption(option, index)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QListWidget()
delegate = StyledItemDelegate(w) # <---
w.setItemDelegate(delegate) # <---
w.setViewMode(QtWidgets.QListView.IconMode)
w.setIconSize(QtCore.QSize(128, 128))
w.setResizeMode(QtWidgets.QListView.Adjust)
for _ in range(20):
it = QtWidgets.QListWidgetItem()
it.setIcon(QtGui.QIcon("light.png"))
w.addItem(it)
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
Another option is to disable the Qt::ItemIsSelectable
flag of the QListWidgetItem:
from PySide2 import QtCore, QtGui, QtWidgets
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
w = QtWidgets.QListWidget()
w.setViewMode(QtWidgets.QListView.IconMode)
w.setIconSize(QtCore.QSize(128, 128))
w.setResizeMode(QtWidgets.QListView.Adjust)
for i in range(20):
it = QtWidgets.QListWidgetItem(str(i))
it.setIcon(QtGui.QIcon("light.png"))
it.setFlags(it.flags() &~ QtCore.Qt.ItemIsSelectable) # <---
w.addItem(it)
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
来源:https://stackoverflow.com/questions/55034075/would-like-not-clickable-highlighted-icons-in-listwidget