Search code examples
pythonpyqt4qlistwidget

Clearing selection in QListWidget


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.


Solution

  • You should be able to do this using setItemSelected()

    Here is a working example of a listWidget with a "clear" button:

    from PyQt4 import QtGui, QtCore
    import sys, random
    
    def clear(listwidget):
        for i in range(listwidget.count()):
            item = listwidget.item(i)
            listwidget.setItemSelected(item, False)
    
    app = QtGui.QApplication([])
    top = QtGui.QWidget()
    
    # list widget
    myListWidget = QtGui.QListWidget(top)
    myListWidget.setSelectionMode(2)
    myListWidget.resize(200,300)
    for i in range(10):
        item = QtGui.QListWidgetItem("item %i" % 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_())
    

    Looks like this:

    enter image description here