我需要获取所选复选框的索引。我不知道如何为复选框和列表项添加索引(实际上我需要获取所选复选框的列表项)。我认为之后可能会获得复选框的索引。
这是我的代码:
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_())
答案 0 :(得分:2)
您的示例代码似乎已经有了大部分答案:
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)