forked from PyQt5/PyQt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DeleteCustomItem.py
99 lines (79 loc) · 2.84 KB
/
DeleteCustomItem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2018年11月4日
@author: Irony
@site: https://pyqt5.com , https://github.com/892768447
@email: [email protected]
@file: 删除Item
@description:
"""
from PyQt5.QtCore import QSize, pyqtSignal
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QLineEdit, QPushButton,\
QListWidgetItem, QVBoxLayout, QListWidget
__Author__ = """By: Irony
QQ: 892768447
Email: [email protected]"""
__Copyright__ = 'Copyright (c) 2018 Irony'
__Version__ = 1.0
class ItemWidget(QWidget):
itemDeleted = pyqtSignal(QListWidgetItem)
def __init__(self, text, item, *args, **kwargs):
super(ItemWidget, self).__init__(*args, **kwargs)
self._item = item # 保留list item的对象引用
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(QLineEdit(text, self))
layout.addWidget(QPushButton('x', self, clicked=self.doDeleteItem))
def doDeleteItem(self):
self.itemDeleted.emit(self._item)
def sizeHint(self):
# 决定item的高度
return QSize(200, 40)
class Window(QWidget):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
layout = QVBoxLayout(self)
# 列表
self.listWidget = QListWidget(self)
layout.addWidget(self.listWidget)
# 清空按钮
self.clearBtn = QPushButton('清空', self, clicked=self.doClearItem)
layout.addWidget(self.clearBtn)
# 添加测试数据
self.testData()
def doDeleteItem(self, item):
# 根据item得到它对应的行数
row = self.listWidget.indexFromItem(item).row()
# 删除item
item = self.listWidget.takeItem(row)
# 删除widget
self.listWidget.removeItemWidget(item)
del item
def doClearItem(self):
# 清空所有Item
for _ in range(self.listWidget.count()):
# 删除item
# 一直是0的原因是一直从第一行删,删掉第一行后第二行变成了第一行
# 这个和删除list [] 里的数据是一个道理
item = self.listWidget.takeItem(0)
# 删除widget
self.listWidget.removeItemWidget(item)
del item
def testData(self):
# 生成测试数据
for i in range(100):
item = QListWidgetItem(self.listWidget)
widget = ItemWidget('item: {}'.format(i), item, self.listWidget)
# 绑定删除信号
widget.itemDeleted.connect(self.doDeleteItem)
self.listWidget.setItemWidget(item, widget)
if __name__ == '__main__':
import sys
import cgitb
sys.excepthook = cgitb.enable(1, None, 5, 'text')
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())