下一步是我的目标:我在qlistwidget中添加了包含将其从列表中删除的按钮的项目。
但是,当我在创建列表项的循环中将带有单击按钮的信号连接到具有删除功能时,则总是尝试删除我的最后一项。
那是代码:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QLabel, QPushButton, QListWidgetItem, \
QHBoxLayout
def remove_item_from_list(listbox, item):
print('was', listbox.count())
print(item)
row = listbox.row(item)
print('row is', row)
listbox.takeItem(row)
print('now is', listbox.count())
class CustomQWidget(QWidget):
def __init__(self, label_text, parent=None):
super(CustomQWidget, self).__init__(parent)
label = QLabel(label_text)
self.button = QPushButton("A useless button")
#self.button.clicked.connect(lambda : )
layout = QHBoxLayout()
layout.addWidget(label)
layout.addWidget(self.button)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
title = QLabel("Demo for widgets in a QListWidget")
labels = ['Cat', 'Dog', 'Person']
list = QListWidget()
for label in labels:
item = QListWidgetItem(list)
print(item)
item_widget = CustomQWidget(label)
item.setSizeHint(item_widget.sizeHint())
#list.addItem(item)
item_widget.button.clicked.connect(lambda: remove_item_from_list(list, item))
list.setItemWidget(item, item_widget)
window_layout = QVBoxLayout(window)
window_layout.addWidget(title)
window_layout.addWidget(list)
window.setLayout(window_layout)
window.show()
sys.exit(app.exec_())
但是,如果我将信号连接到每个项目窗口小部件类中,那么就会得到所需的结果。 改变了:
class CustomQWidget(QWidget):
def __init__(self, label_text, parent_item, parent_widget=None):
super(CustomQWidget, self).__init__(parent_widget)
label = QLabel(label_text)
self.button = QPushButton("A useless button")
self.button.clicked.connect(lambda: remove_item_from_list(parent_widget, parent_item))
layout = QHBoxLayout()
layout.addWidget(label)
layout.addWidget(self.button)
self.setLayout(layout)
从创建项目的循环中删除了信号连接:
for label in labels:
item = QListWidgetItem(list)
item_widget = CustomQWidget(label, item, list)
item.setSizeHint(item_widget.sizeHint())
list.setItemWidget(item, item_widget)
所以问题是为什么第一种方法不起作用?