Search code examples
pythonfocusselectionpysideqlistwidget

How to remove focus from QListWidget item


I am using PySide and I have a QListWidget. I made a dummy item and placed it at the top of the QListWidget. I did this so when the tool first opens, no useful item is selected by default. I do not like that this empty item is "highlighted", revealing the item to the user. How can I get rid of this outline/highlight? I will include an image of the issue:

enter image description here


Solution

  • You can achieve this with an item-delegate:

    class NoFocusDelegate(QStyledItemDelegate):
        def paint(self, painter, option, index):
            option.state = QStyle.State_None
            super(NoFocusDelegate, self).paint(painter, option, index)
    
    self.listWidget.setItemDelegateForRow(0, NoFocusDelegate(self))
    

    However, a better solution would be to get rid of the dummy item and just clear the focus by setting an invalid current index:

    self.listWidget.setCurrentIndex(QModelIndex())
    

    Now no item will be highlighted, and currentItem() will return None and currentRow() will return -1 until the user explicitly selects an item.