简体   繁体   中英

PyQt - trigger an event when nothing is selected in a QListWidget?

I have an object of type QListWidget where the user can select 0 or more items.

If nothing is selected, how can i trigger an event that would call a function? I know that you can detect clicking on a specific item by using:

QListWidget.itemClicked.connect(self.item_click)

Is there something similar for when nothing is selected at all? (or in other words, the QListWidget is clear)

Thanks!

Generally, you would connect to the itemSelectionChanged signal and then check whether anything is selected.

self.listwidget.itemSelectionChanged.connect(self.on_selection_changed)

def on_selection_changed(self):
    if not self.listwidget.selectedItems():
        # Do Stuff Here
        self.nothing_selected_function()

But that will only catch events where something was selected and then the user deselected everything. If nothing was ever selected, it's not going to trigger this signal (like the first time you build the list, and nothing is selected). You'd have to call the slot manually in that case.

self.listwidget = ...  # Code that builds and populates list widget
# Call this manually the first time.
self.on_selection_changed()

But part of your question is ambiguous. Why do you want to know when something is "not selected"? What about when a new item is added to the list? Should it trigger your "not selected" function since the list has changed, but there still isn't anything selected?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM