Reputation: 4035
I have QListWidget and there are strings there, when I select a string, I wanted to display the index number and text of that. But the problem is, if I select more than 1 items, it doesn't display all of the indexes. It displays only one.
from PyQt5.QtWidgets import *
import sys
class Pencere(QWidget):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout(self)
self.listwidget = QListWidget(self)
self.listwidget.addItems(["Python","Ruby","Go","Perl"])
self.listwidget.setSelectionMode(QAbstractItemView.MultiSelection)
self.buton = QPushButton(self)
self.buton.setText("Ok")
self.buton.clicked.connect(self.but)
self.layout.addWidget(self.listwidget)
self.layout.addWidget(self.buton)
def but(self):
print (self.listwidget.currentRow()+1)
uygulama = QApplication(sys.argv)
pencere = Pencere()
pencere.show()
uygulama.exec_()
How can I display all of the items names and indexes if I select more than 1 items?
Upvotes: 0
Views: 1843
Reputation: 4035
I solved it with this
def but(self):
x = self.listwidget.selectedItems()
for y in x:
print (y.text())
Upvotes: 1
Reputation: 744
You need to use QListWidget's selectedItems()
function, which returns a list. currentRow()
only returns a single integer, and is intended to be used only in single-selection instances.
Once you've got the list of QListWidgetItems, you can use the text()
function on each item to retreive the text.
Getting the index is slightly more complicated, you'll have to get a QModelIndex
object from your original QListWidgetItem
using the QListWidget.indexFromItem()
and then use the QModelIndex.row()
function.
Source: http://pyqt.sourceforge.net/Docs/PyQt4/qlistwidget.html#selectedItems
Note: You specified PyQt5 in your tags, but the API of QListWidget remains the same in this case; see the C++ API docs if you want to make sure.
Upvotes: 0