gpt4 book ai didi

python - 获取 QListWidget 中选中复选框的索引

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:11 24 4
gpt4 key购买 nike

我需要获取选中复选框的索引。我不知道如何为复选框和列表项添加索引(实际上我需要获取所选复选框的列表项)。我认为之后可能可以获得复选框的索引。

这是我的代码:

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_())

最佳答案

您的示例代码似乎已经有了大部分答案:

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)

关于python - 获取 QListWidget 中选中复选框的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29368331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com