Search code examples
pythonpyqtpyqt5qlistwidget

Is it possible to restrict QListWidget so users can only select 3 items max?


I know that you can change the selection mode to select more than one item from a list. However, changing to multiselection means users can choose to select all items in a list if they wanted to. I was wondering if it was possible to allow users to select multiple items but set a max number of items (ie users can select 1-3 items from a list of 20 items).

I've looked through the documentation and various questions, but can't see any methods that would do this.

import sys
from PyQt5.QtWidgets import QAbstractItemView, QApplication, QListWidget, QListWidgetItem, QVBoxLayout, QWidget

class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.setGeometry(50,50,320,200)
        layout = QVBoxLayout(self)
        combo = QListWidget(self)
        combo.setSelectionMode(QAbstractItemView.MultiSelection)
        counter = 1
        while (counter < 21):
            combo.addItem(str(counter))
            counter = counter + 1
        layout.addWidget(combo)
        self.setWindowTitle("QListWidget")
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

My example code displays a list of 20 items. It has multiselection set so users can select multiple but no current restrictions.


Solution

  • One way is to subclass QListWidget and override selectionCommand, e.g.

    from PyQt5.QtCore import QItemSelectionModel
    
    class MyListWidget(QListWidget):
        def __init__(self, parent=None, max_selected = 3):
            super().__init__(parent)
            self.max_selected = max_selected
    
        def selectionCommand(self, index, event):
            if len(self.selectedItems()) >= self.max_selected:
                return QItemSelectionModel.Deselect
            else:
                return super().selectionCommand(index, event)