Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 430
Rao Avatar asked Dec 05 '22 12:12

Rao


2 Answers

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_())
like image 61
rutsky Avatar answered Dec 07 '22 01:12

rutsky


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

like image 36
Junuxx Avatar answered Dec 07 '22 01:12

Junuxx