Search code examples
pythoncheckboxpyqt4selectionqlistwidget

Get the index of selected checkboxes in a QListWidget


I need to get the index of the selected checkboxes. I don't know how to add an index to both the checkbox and the list item (actually I need to get the list items of the selected checkboxes). I think it may be possible afterwards to get the index of the checkboxes.

This is my code:

from PyQt4 import QtGui, QtCore
from PyQt4.Qt import SIGNAL, SLOT, QMainWindow, qApp, QUrl, QImage,\
QStringListModel
from PyQt4.QtCore import Qt
import sys
import os

class ThumbListWidget(QtGui.QListWidget):

    def __init__(self, type, parent=None):
        super(ThumbListWidget, self).__init__(parent)
        self.setIconSize(QtCore.QSize(124, 124))
        self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.setAcceptDrops(True)
        self.setSelectionRectVisible(True)

    def keyPressEvent(self, event):

        if event.key() == Qt.Key_Space:
            if self.selectedItems():
                new_state = Qt.Unchecked if self.selectedItems()[0].checkState() else Qt.Checked
                for item in self.selectedItems():
                    if item.flags() & Qt.ItemIsUserCheckable:
                        item.setCheckState(new_state)

            self.viewport().update()

        elif event.key() == Qt.Key_Delete:
            for item in self.selectedItems():
                self.takeItem(self.row(item))

    def iterAllItems(self):
        for i in range(self.count()):
            yield self.item(i)

class Dialog(QtGui.QMainWindow):

    def __init__(self):
        super(QtGui.QMainWindow, self).__init__()
        self.listItems = {}

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)

        self.listWidgetA = ThumbListWidget(self)
        for i in range(5):
            QtGui.QListWidgetItem('Item ' + str(i + 1), self.listWidgetA)

        for item in self.listWidgetA.iterAllItems():
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.UnChecked)

        myBoxLayout.addWidget(self.listWidgetA)
        self.listWidgetA.setAcceptDrops(False)
        self.listWidgetA.viewport().update()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog = Dialog()
    dialog.show()
    dialog.resize(400, 140)
    sys.exit(app.exec_())

Solution

  • Your example code seems to have most of the answer already:

    class ThumbListWidget(QtGui.QListWidget):
        ...
    
        def checkedItems(self):
            for index in range(self.count()):
                item = self.item(index)
                if item.checkState() == Qt.Checked:
                    yield index, item
    

    Or you could just return the item, and then get the index like this:

        index = listWidget.row(item)