how to get the checked items listed in a qt qlistwidget

  • Last Update :
  • Techknowledgy :

You need to check if checkState is actually Qt.Checked:

for index in range(self.listWidgetLabels.count()):
   if self.listWidgetLabels.item(index).checkState() == Qt.Checked:
   checked_items.append(self.listWidgetLabels.item(index).text())

Suggestion : 2

To make items checkable, we subclass the QStringListModel. We introduce a container that will store the checked items, namely QSet<QPersistentModelIndex> checkedItems and override the methods data(), setData() and flags().,To make items checkable, we have to override the method flags() and equip the items with an extra flag Qt::ItemIsUserCheckable.,Unlike the previous implementation, this implementation employs QListView and subclasses QStringListModel. Below is the header customdialog.h, which stores a pointer to an instance of QListView and a custom model instance CustonListModel.,Variant 2 - a more complex solution that employs QListView and a subclassed QStringListModel. This solution is more suitable for problems that require additional capabilities (other than checking and unchecking). This approach requires that we override methods flags(), data() and setData().

This variant of the implementation uses QListWidget to obtain the desired functionality. The header customdialog.h can be seen below. The checkable list is represented by QListWidget. To make the items checkable, we have to add a flag Qt::ItemIsUserCheckable. Anytime we check an item, we also trigger a slot highlightChecked() which highlights the checked items in yellow.

class CustomDialog: public QDialog {
   Q_OBJECT
   public:
      CustomDialog(QWidget * parent = 0);
   public slots:
      void highlightChecked(QListWidgetItem * item);
   void save();
   private:
      QListWidget * widget;
   QDialogButtonBox * buttonBox;
   QGroupBox * viewBox;
   QPushButton * saveButton;
   QPushButton * closeButton;

   void createListWidget();
   void createOtherWidgets();
   void createLayout();
   void createConnections();
};

In the constructor we initialize all the widgets, populate the list widget with data, create the necessary layouts and connections.

CustomDialog::CustomDialog(QWidget * parent): QDialog(parent) {
   setWindowTitle("Checkable list in Qt");

   createListWidget();
   createOtherWidgets();
   createLayout();
   createConnections();
}

The method createListWidget() can be seen below. We populate the list widget with the method addItems(QStringList). Once the items have been created, we enable checking/unchecking of the items with the flag Qt::ItemIsUserCheckable. This flag is all that is necessary to make items checkable. We also set the default state of the items to Qt::Unchecked.

void CustomDialog::createListWidget() {
   widget = new QListWidget;
   QStringList strList;
   strList << "monitor" << "mouse" << "keyboard" << "hard disk drive" <<
      "graphic card" << "sound card" << "memory" << "motherboard";

   widget - > addItems(strList);

   QListWidgetItem * item = 0;
   for (int i = 0; i < widget - > count(); ++i) {
      item = widget - > item(i);
      item - > setFlags(item - > flags() | Qt::ItemIsUserCheckable);
      item - > setCheckState(Qt::Unchecked);
   }
}

The slot highlightChecked(QListWidgetItem*) can be seen below. The method renders the background of checked items in light yellow, the background of unchecked items remains white.

void CustomDialog::highlightChecked(QListWidgetItem * item) {
   if (item - > checkState() == Qt::Checked)
      item - > setBackgroundColor(QColor("#ffffb2"));
   else
      item - > setBackgroundColor(QColor("#ffffff"));
}

Unlike the previous implementation, this implementation employs QListView and subclasses QStringListModel. Below is the header customdialog.h, which stores a pointer to an instance of QListView and a custom model instance CustonListModel.

class CustomDialog: public QDialog {
   Q_OBJECT
   public:
      CustomDialog(QWidget * parent = 0);
   public slots:
      void save();
   private:
      CustomListModel * model;
   QListView * view;
   QDialogButtonBox * buttonBox;
   QGroupBox * viewBox;
   QPushButton * saveButton;
   QPushButton * closeButton;

   void createListModelView();
   void createOtherWIdgets();
   void createLayout();
   void createConnections();
};

Note: The conditional statement

    if (role == Qt::CheckStateRole)
       return checkedItems.contains(index) ?
          Qt::Checked : Qt::Unchecked;

is nothing else than:

    if (role == Qt::CheckStateRole) {
       if (checkedItems.contains(index))
          return Qt::Checked;
       else
          return Qt::Unchecked;
    }

Suggestion : 3

The selectionMode() of a list widget determines how many of the items in the list can be selected at the same time, and whether complex selections of items can be created. This can be set with the setSelectionMode() function.,The QListWidget class provides an item-based list widget. More...,QListWidget is a convenience class that provides a list view similar to the one supplied by QListView, but with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list.,Returns a list of pointers to the items contained in the data object. If the object was not created by a QListWidget in the same process, the list is empty.

    QListWidget * listWidget = new QListWidget(this);
    new QListWidgetItem(tr("Oak"), listWidget);
    new QListWidgetItem(tr("Fir"), listWidget);
    new QListWidgetItem(tr("Pine"), listWidget);
    QListWidgetItem * newItem = new QListWidgetItem;
    newItem - > setText(itemText);
    listWidget - > insertItem(row, newItem);

Suggestion : 4

last modified August 9, 2022

1._
#!/usr/bin/python

import sys
from PyQt6.QtWidgets import(QListWidget, QWidget, QMessageBox,
   QApplication, QVBoxLayout)

class Example(QWidget):

   def __init__(self):
   super().__init__()

self.initUI()

def initUI(self):

   vbox = QVBoxLayout(self)

listWidget = QListWidget()

listWidget.addItem("sparrow")
listWidget.addItem("robin")
listWidget.addItem("crow")
listWidget.addItem("raven")
listWidget.addItem("woodpecker")
listWidget.addItem("hummingbird")

listWidget.itemDoubleClicked.connect(self.onClicked)

vbox.addWidget(listWidget)
self.setLayout(vbox)

self.setGeometry(400, 300, 350, 250)
self.setWindowTitle('QListWidget')
self.show()

def onClicked(self, item):

   QMessageBox.information(self, "Info", item.text())

def main():

   app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())

if __name__ == '__main__':
   main()

We create a QListWidget which has names of birds as its items. By double-clicking an item, the current bird name is shown in a message box.

listWidget = QListWidget(self)

A QListWidget is created.

listWidget.addItem("sparrow")
listWidget.addItem("robin")
listWidget.addItem("crow")
   ...

We connect the onClicked function to the itemDoubleClicked signal.

def onClicked(self, item):

   QMessageBox.information(self, "Info", item.text())
6._
#!/usr/bin/python


import sys
from PyQt6.QtWidgets import(QListWidget, QPushButton, QWidget, QHBoxLayout,
   QMessageBox, QApplication, QVBoxLayout)

class Example(QWidget):

   def __init__(self):
   super().__init__()

self.initUI()

def initUI(self):

   vbox = QVBoxLayout(self)
hbox = QHBoxLayout()

self.listWidget = QListWidget(self)

self.listWidget.addItems(['sparrow', 'robin', 'crow', 'raven',
   'woopecker', 'hummingbird'
])

clearBtn = QPushButton('Clear', self)
clearBtn.clicked.connect(self.onClearClicked)

countBtn = QPushButton('Count', self)
countBtn.clicked.connect(self.onCountClicked)

vbox.addWidget(self.listWidget)
hbox.addWidget(clearBtn)
hbox.addWidget(countBtn)
vbox.addLayout(hbox)

self.setLayout(vbox)

self.setGeometry(400, 300, 350, 250)
self.setWindowTitle('QListWidget')
self.show()

def onClearClicked(self):

   self.listWidget.clear()

def onCountClicked(self):

   QMessageBox.information(self, "Info",
      f '# of birds {self.listWidget.count()}')

def main():

   app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())

if __name__ == '__main__':
   main()