Python:如何在PyQt中查询QListWidget中的多个选定项

时间:2014-03-27 23:01:59

标签: python qlistwidget

启用了ExtendedSelection的单个QListWidget(可以同时选择多个项目)。单击按钮查询listWidget.currentItem()以从listWidget获取当前项。问题:如何获取listWidget中当前选中的所有项目?

from PyQt4 import QtGui, QtCore
import sys, os

class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow,self).__init__()

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)

        self.listWidget = QtGui.QListWidget()
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)

        for i in range(3):
            item=QtGui.QListWidgetItem()
            name='A'+'%04d'%i
            item.setText(name)                        
            self.listWidget.addItem(item) 

        myBoxLayout.addWidget(self.listWidget)      

        Button_01 = QtGui.QPushButton("Print Current Items")
        Button_01.clicked.connect(self.printCurrentItems)
        myBoxLayout.addWidget(Button_01)


    def printCurrentItems(self):
        print "Current Items are : ", self.listWidget.currentItem()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog_1 = Dialog_01()
    dialog_1.show()
    dialog_1.resize(720,480)
    sys.exit(app.exec_())

2 个答案:

答案 0 :(得分:2)

这是工作代码(感谢user3254944!):

from PyQt4 import QtGui, QtCore
import sys, os

class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow,self).__init__()

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)

        self.listWidget = QtGui.QListWidget()
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)

        for i in range(3):
            item=QtGui.QListWidgetItem()
            name='A'+'%04d'%i
            item.setText(name)                        
            self.listWidget.addItem(item) 

        myBoxLayout.addWidget(self.listWidget)      

        Button_01 = QtGui.QPushButton("Print Current Items")
        Button_01.clicked.connect(self.printCurrentItems)
        myBoxLayout.addWidget(Button_01)


    def printCurrentItems(self):
        print "Current Items are : ", self.listWidget.selectedItems()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog_1 = Dialog_01()
    dialog_1.show()
    dialog_1.resize(720,480)
    sys.exit(app.exec_())

答案 1 :(得分:1)

.selectedItems()

QTableWidget的C ++,QListWidget

的C ++
QList<QTableWidgetItem*> selectedItems = matrixTable.selectedItems();