QListWidget and Multiple Selection

此生再无相见时 提交于 2019-11-30 01:06:01

问题


I have a regular QListWidget with couple of signals and slots hookedup. Everything works as I expect. I can update, retrieve, clear etc.

But the UI wont support multiple selections.

How do I 'enable' multiple selections for QListWidget? My limited experience with PyQt tells me I need to create a custom QListWidget by subclassing .. but what next?

Google gave me C++ answers but I'm looking for Python

http://www.qtforum.org/article/26320/qlistwidget-multiple-selection.html

http://www.qtcentre.org/threads/11721-QListWidget-multi-selection


回答1:


Unfortunately I can't help with the Python specific syntax but you don't need to create any subclasses.

After your QListWidget is created, call setSelectionMode() with one of the multiple selection types passed in, probably QAbstractItemView::ExtendedSelection is the one you want. There are a few variations on this mode that you may want to look at.

In your slot for the itemSelectionChanged() signal, call selectedItems() to get a QList of QListWidgetItem pointers.




回答2:


For PyQT4 it's

QListWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)



回答3:


Example of getting multiple selected values in listWidget with multiple selection.

from PyQt5 import QtWidgets, QtCore
class Test(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Test, self).__init__(parent)
        self.layout = QtWidgets.QVBoxLayout()
        self.listWidget = QtWidgets.QListWidget()
        self.listWidget.setSelectionMode(
            QtWidgets.QAbstractItemView.ExtendedSelection
        )
        self.listWidget.setGeometry(QtCore.QRect(10, 10, 211, 291))
        for i in range(10):
            item = QtWidgets.QListWidgetItem("Item %i" % i)
            self.listWidget.addItem(item)
        self.listWidget.itemClicked.connect(self.printItemText)
        self.layout.addWidget(self.listWidget)
        self.setLayout(self.layout)

    def printItemText(self):
        items = self.listWidget.selectedItems()
        x = []
        for i in range(len(items)):
            x.append(str(self.listWidget.selectedItems()[i].text()))

        print (x)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    form = Test()
    form.show()
    app.exec_()

output :-



来源:https://stackoverflow.com/questions/4008649/qlistwidget-and-multiple-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!