2015-03-31 69 views
2

我需要獲取所選複選框的索引。我不知道如何將一個索引添加到複選框和列表項(實際上我需要獲取所選複選框的列表項)。我想以後可能會得到複選框的索引。獲取QListWidget中選定複選框的索引

這是我的代碼:

from PyQt4 import QtGui, QtCore 
from PyQt4.Qt import SIGNAL, SLOT, QMainWindow, qApp, QUrl, QImage,\ 
QStringListModel 
from PyQt4.QtCore import Qt 
import sys 
import os 

class ThumbListWidget(QtGui.QListWidget): 

    def __init__(self, type, parent=None): 
     super(ThumbListWidget, self).__init__(parent) 
     self.setIconSize(QtCore.QSize(124, 124)) 
     self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) 
     self.setAcceptDrops(True) 
     self.setSelectionRectVisible(True) 

    def keyPressEvent(self, event): 

     if event.key() == Qt.Key_Space: 
      if self.selectedItems(): 
       new_state = Qt.Unchecked if self.selectedItems()[0].checkState() else Qt.Checked 
       for item in self.selectedItems(): 
        if item.flags() & Qt.ItemIsUserCheckable: 
         item.setCheckState(new_state) 

      self.viewport().update() 

     elif event.key() == Qt.Key_Delete: 
      for item in self.selectedItems(): 
       self.takeItem(self.row(item)) 

    def iterAllItems(self): 
     for i in range(self.count()): 
      yield self.item(i) 

class Dialog(QtGui.QMainWindow): 

    def __init__(self): 
     super(QtGui.QMainWindow, self).__init__() 
     self.listItems = {} 

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

     self.listWidgetA = ThumbListWidget(self) 
     for i in range(5): 
      QtGui.QListWidgetItem('Item ' + str(i + 1), self.listWidgetA) 

     for item in self.listWidgetA.iterAllItems(): 
      item.setFlags(item.flags() | Qt.ItemIsUserCheckable) 
      item.setCheckState(Qt.UnChecked) 

     myBoxLayout.addWidget(self.listWidgetA) 
     self.listWidgetA.setAcceptDrops(False) 
     self.listWidgetA.viewport().update() 

if __name__ == '__main__': 
    app = QtGui.QApplication(sys.argv) 
    dialog = Dialog() 
    dialog.show() 
    dialog.resize(400, 140) 
    sys.exit(app.exec_()) 

回答

1

你的示例代碼似乎有大部分的答案已經是:

class ThumbListWidget(QtGui.QListWidget): 
    ... 

    def checkedItems(self): 
     for index in range(self.count()): 
      item = self.item(index) 
      if item.checkState() == Qt.Checked: 
       yield index, item 

或者你可以回報的項目,然後得到這樣的指標:

index = listWidget.row(item) 
+0

非常感謝你...... – 2015-04-07 07:24:35