Clearing selection in QListWidget

Rao picture Rao · Feb 26, 2013 · Viewed 12.9k times · Source

I'm using PyQt4 and I have a QListWidget in a window where I added items to it at run-time. I want to use a button in the window to clear the selection of the QListWidget.

I want to know if there is any approach to achieve this?

I checked clear() but it clears the items in the listwidget, but I want to clear the selection in the listwidget.

Answer

rutsky picture rutsky · Apr 14, 2015

Use list_widget.selectionModel().clear() or list_widget.clearSelection() (thanks, @ekhumoro!).

I modified example by Junuxx:

from PyQt4 import QtGui, QtCore
import sys, random

def clear(listwidget):
    #listwidget.selectionModel().clear()
    listwidget.clearSelection()

app = QtGui.QApplication(sys.argv)
top = QtGui.QWidget()

# list widget
myListWidget = QtGui.QListWidget(top)
myListWidget.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
myListWidget.resize(200, 300)
for i in range(10):
    item = QtGui.QListWidgetItem("item {}".format(i), myListWidget)
    myListWidget.addItem(item)
    if random.random() > 0.5: 
        # randomly select half of the items in the list
        item.setSelected(True)

# clear button
myButton = QtGui.QPushButton("Clear", top)
myButton.resize(60, 30)
myButton.move(70, 300)
myButton.clicked.connect(lambda: clear(myListWidget))
top.show()

sys.exit(app.exec_())