Python Forum

Full Version: QListWidget, no item was selected
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

if I have a listwidget, is it possible to detect if no item of the listwidget was selected?

I searched the web, but found nothing helpful...

amount_of_selected_items = self.listbox_profile.selectedItems().count()
if amount_of_selected_items == 0:
    QMessageBox("text")
thanks...
try

amount_of_selected_items = len(self.listbox_profile.selectedItems())
Do you need to know the number? You don't if you are only checking if there are selected items. You can do this instead.
if not self.listbox_profile.selectedItems():
    QMessageBox("text")
Hi,
Axel_Erfurt and deanhystad...

Thanks a lot for your answers!!

The solution from Axel_Erfurt works good.

I don't know what I'm doing wrong, but the solution from deanhystad doesn't work in my code...

Never mind...

I wish you a pleasant day!!

Greetings...
deanhystad's solution also works.

import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow,  QGridLayout, QListWidget)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Test')
        self.setGeometry(100, 100, 400, 100)
        
        self.list_widget = QListWidget()
        self.list_widget.addItems(['Hello', 'World'])
        self.setCentralWidget(self.list_widget)
        
        self.check_selected()
        
        self.list_widget.setCurrentRow(1)
        
        self.check_selected()
        
        self.show()
        
        
    def check_selected(self):
        if not self.list_widget.selectedItems():
            print("nothing selected")
        else:
            print(f"row {self.list_widget.currentRow()} selected")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())
Output:
nothing selected row 1 selected