Search code examples
pythonpyqt5qlistwidget

QListWidget show item number near text


Is there any simple way to add the row number (start = 1) left the item text?

I know how can i do it manually, but then if i delete or reorder the items i should change that numbers.

So why i am asking, for a simple way.

I search in documentation, but i don't found something for that. Also Qt Designer hasn't something about.

I have a QListWidget like this in the image (the right frame shows details of selected item)

enter image description here


Solution

  • Use a delegate:

    class Delegate(QStyledItemDelegate):
        def initStyleOption(self, option, index):
            super().initStyleOption(option, index)
            option.text = f"{index.row() + 1}. {option.text}"
    
    delegate = Delegate(listWidget)
    listWidget.setItemDelegate(delegate)