How is ContiguousSelection mode set in QListWiget using Python?

24 Views Asked by At

How can we set the 'ContiguousSelection' mode for a QListWidget in Python?

My problem seems to be in accessing the QAbstractView modes, as given in the QAbstractItemView docs.

See: https://doc.qt.io/qt-6/qabstractitemview.html#setSelectionModel

See: https://doc.qt.io/qt-6/qabstractitemview.html#selectionMode-prop

(I am running on a Windows machine.)

Here is my MRC:

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

class MainWindow(QMainWindow):

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

        self.setWindowTitle("My App")

        self.widget = QListWidget()
        self.setCentralWidget(self.widget)
        
        self.widget.addItems(["One", "Two", "Three", "Four", "Five", "Six"])
        self.widget.currentItemChanged.connect(self.index_changed)
        
        print("\n>> self.widget.setSelectionMode(QAbstractItemView:ContiguousSelection)\n\
 as listed in the docs, throws 'invalid Syntex' exception.")
        #self.widget.setSelectionMode(QAbstractItemView:ContiguousSelection)
        
        try:
            self.widget.setSelectionMode(QAbstractItemView.ContiguousSelection)
        except:
            print(">> self.widget.setSelectionMode(QAbstractItemView.ContiguousSelection)\n Fails.")
        print('-='*35,end='\n\n')
        
        print("(By default, only one item can be selected at a time.)".center(80))
    
    def index_changed(self, i): # Not an index, i is a QListWidgetItem
        print(i.text())

app = QApplication([])
window = MainWindow()
window.show()
app.exec()

-- Variations I have tried --

self.widget.setSelectionMode(QAbstractItemView:ContiguousSelection)

This version, as listed in the docs, causes the compiler to throw an 'invalid Syntax' error.

self.widget.setSelectionMode(QAbstractItemView.ContiguousSelection)

This version fails with the error message: type object 'QAbstractItemView' has no attribute 'ContiguousSelection'.

Thank you for any help you can give.

0

There are 0 best solutions below