Search code examples
pythonpyqtqlistwidget

How can I edit a QListWidget item without removing it to edit and adding back?


I would like to edit listWidget items that are selected via a button programmatically. I am not entirely sure if there is a way to edit selected items without having to remove the original items and add the new edit back in.

I saw this... but I am not sure this is what I need, as I can't pass in a new value:

selItems = listWidget.selectedItems()

for item in selItems:
    listWidget.editItem(item, "test")

TypeError: QListWidget.editItem(QListWidgetItem): too many arguments

Solution

  • The editItem method is used when you want the user to edit the item. If the item is editable, by default, it will create a QLineEdit widget in the cell for the user to edit the text, unless you've created a QItemDelegate to create a different widget for editing.

    To change the text of an item, just use setText(). You can use text() to get the current text of the item.

    sel_items = listWidget.selectedItems()
    
    for item in sel_items:
        item.setText(item.text() + ' plus more text')