Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected item QlistWidget pyqt

Tags:

python

pyqt5

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

like image 565
Ahmed007 Avatar asked Nov 09 '17 11:11

Ahmed007


3 Answers

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.

like image 112
Szabolcs Avatar answered Nov 07 '22 21:11

Szabolcs


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.

like image 4
Erik Šťastný Avatar answered Nov 07 '22 22:11

Erik Šťastný


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.

like image 2
ekohrt Avatar answered Nov 07 '22 21:11

ekohrt