Ahmed007
Ahmed007

Reputation: 201

How to get selected item QlistWidget pyqt

I want to get selected element when the user selects an item in QlistWidget then clicked button to get this element

Upvotes: 8

Views: 37367

Answers (3)

ekohrt
ekohrt

Reputation: 51

Binding a method to the itemClicked signal from QListWidget also seems to work:

yourQListWidget.itemClicked.connect(itemClicked_event)

def itemClicked_event(item):
    print(item.text())

For me, the itemClicked signal works with single-clicking the item and itemActivated works with double clicking.

Upvotes: 2

Szabolcs
Szabolcs

Reputation: 4106

Try this one:

from PyQt5.QtWidgets import (QWidget, QListWidget, QVBoxLayout, QApplication)
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()


        self.l = QListWidget()
        for n in range(10):
            self.l.addItem(str(n))

        self.l.itemSelectionChanged.connect(self.selectionChanged)

        vbox = QVBoxLayout()
        vbox.addWidget(self.l)

        self.setLayout(vbox)
        self.setGeometry(300, 300, 300, 300)
        self.show()

    def selectionChanged(self):
        print("Selected items: ", self.l.selectedItems())


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

With this approach you will have all items, selected by clicking, using keyboard arrows or dragging the mouse on them, printed.

Upvotes: 10

Erik Šťastný
Erik Šťastný

Reputation: 1486

You can use itemActivated signal from QListWidget class and bind it to some of your method.

yourQListWidget.itemActivated.connect(itemActivated_event)

def itemActivated_event(item)
    print(item.text())

Now everytime user click on some item in your QListWidget the text inside of this item is printed.

Upvotes: 4

Related Questions