Signal when an item is added or removed to a QListWidget
Asked Answered
T

2

5

I dynamically add and remove items to a QListWidget based on user selections elsewhere in the application. Is there a signal that is emitted when items are added or removed to a QListWidget? The signals that I see in the documentation doesn't mention anything for Add or Remove. The rest of the signals are for when individual items are interacted with.

How can I be notified when an item is added to my QListWidget?

A very simple example:

from PyQt4.QtGui import *
import sys

app = QApplication(sys.argv)
listWidget = QListWidget()

for i in range(10):
    item = QListWidgetItem("Item %i" % i)
    listWidget.addItem(item)
    # ^^^ This is what I want a signal on

listWidget.show()
sys.exit(app.exec_())

What signal can I utilize to capture that addItem event?

Tugboat answered 16/3, 2015 at 15:15 Comment(0)
H
10

You need to get hold of the implied model object within the widget:

model = listWidget.model()

This has a rowsInserted signal that you can connect. See http://doc.qt.io/qt-4.8/qabstractlistmodel-members.html

Hap answered 16/3, 2015 at 17:35 Comment(0)
K
4

Complementing what was answered above, connecting your_listWidget which is a QListWidget to capture any addition or removal of rows would look like this:

    your_listWidget.model().rowsInserted.connect(lambda: your_function)
    your_listWidget.model().rowsRemoved.connect(lambda: your_function)
Knur answered 13/8, 2020 at 21:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.