forked from PyQt5/PyQt
-
Notifications
You must be signed in to change notification settings - Fork 6
/
FoldWidget.py
86 lines (66 loc) · 2.53 KB
/
FoldWidget.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2019年5月27日
@author: Irony
@site: https://pyqt.site , https://github.com/PyQt5
@email: [email protected]
@file: FoldWidget
@description: 自定义item折叠控件仿QTreeWidget
"""
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QWidget, QPushButton, QFormLayout, \
QLineEdit, QListWidget, QListWidgetItem, QCheckBox
class CustomWidget(QWidget):
def __init__(self, item, *args, **kwargs):
super(CustomWidget, self).__init__(*args, **kwargs)
self.oldSize = None
self.item = item
layout = QFormLayout(self)
layout.addRow('我是label', QLineEdit(self))
layout.addRow('点击', QCheckBox(
'隐藏下面的按钮', self, toggled=self.hideChild))
self.button = QPushButton('我是被隐藏的', self)
layout.addRow(self.button)
def hideChild(self, v):
self.button.setVisible(not v)
# 这里很重要 当隐藏内部子控件时 需要重新计算高度
self.adjustSize()
def resizeEvent(self, event):
# 解决item的高度问题
super(CustomWidget, self).resizeEvent(event)
self.item.setSizeHint(QSize(self.minimumWidth(), self.height()))
class CustomButton(QPushButton):
# 按钮作为开关
def __init__(self, item, *args, **kwargs):
super(CustomButton, self).__init__(*args, **kwargs)
self.item = item
self.setCheckable(True) # 设置可选中
def resizeEvent(self, event):
# 解决item的高度问题
super(CustomButton, self).resizeEvent(event)
self.item.setSizeHint(QSize(self.minimumWidth(), self.height()))
class Window(QListWidget):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
for _ in range(3):
# 开关
item = QListWidgetItem(self)
btn = CustomButton(item, '折叠', self, objectName='testBtn')
self.setItemWidget(item, btn)
# 被折叠控件
item = QListWidgetItem(self)
# 通过按钮的选中来隐藏下面的item
btn.toggled.connect(item.setHidden)
self.setItemWidget(item, CustomWidget(item, self))
if __name__ == '__main__':
import sys
import cgitb
cgitb.enable(format='text')
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
# 通过qss改变按钮的高度
app.setStyleSheet('#testBtn{min-height:40px;}')
w = Window()
w.show()
sys.exit(app.exec_())