would like not clickable/highlighted icons in listWidget

房东的猫 提交于 2021-02-05 08:07:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!