PyQt4 - 从QListWidget中移除项小部件

8 投票
3 回答
27695 浏览
提问于 2025-04-17 02:40

我有一个 QListWidget(列表控件),需要删除一些项目。

根据我的研究,这通常是个麻烦事。

我看了很多解决方案,但没有一个适合我的具体情况。
目前,我只能处理实际的项目小部件,而不是它们的值或索引。

这是因为我通过 .selectedItems() 方法获取需要删除的项目。

这是我的代码:

ItemSelect = list(self.ListDialog.ContentList.selectedItems())

for x in range (0, len(ItemSelect)):
    print self.ListDialog.ContentList.removeItemWidget(ItemSelect[x])

但是,这段代码根本没有任何作用。
它没有报错,但选中的项目并没有被删除。
我看到的删除项目的方法都需要项目的索引或名称,而我这两样都没有。我只有实际的小部件。

我该怎么删除它们呢?

我是不是漏掉了什么?

我使用的是:

Python 2.7.1
PyQt4
IDLE 1.8
Windows 7

3 个回答

2

这真奇怪,居然没有直接的方法可以从 QListWidget 中删除项目……试试这个:

listWidget = self.ListDialog.ContentList
model = listWidget.model()
for selectedItem in listWidget.selectedItems():
    qIndex = listWidget.indexFromItem(selectedItem)
    print 'removing : %s' %model.data(qIndex).toString()
    model.removeRow(qIndex.row())
8

从列表小部件中删除一个项目:

item = self.listWidget.takeItem(self.listWidget.currentRow())
item = None
17

takeItem() 这个函数应该可以用:

for SelectedItem in self.ListDialog.ContentList.selectedItems():
    self.ListDialog.ContentList.takeItem(self.ListDialog.ContentList.row(SelectedItem))

撰写回答