I want to get selected element when the user selects an item in QlistWidget then clicked button to get this element
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With