目录
效果:
1. 初始显示
2. 更换组件,在本例中是将原有组件都清空重新创建组件放入
代码:
import sys
from PyQt5 import QtCore,QtGui,QtWidgets
class ExampleWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.temp_mark = 0
self.init_data()
self.init_ui()
self.fill_pic_widget()
def init_data(self):
self.pic_file_name_list = ['000', '001', '002', '003', '004', '005', '006', '007', '008', '009', '010', '011',
'012', '013', '014', '015', '016', '017']
pass
def init_ui(self):
self.setWindowTitle('QScrollArea动态放置控件例子')
one_btn = QtWidgets.QPushButton('换内容')
one_btn.clicked.connect(self.one_btn_clicked)
self.pic_layout = QtWidgets.QGridLayout()
self.scroll_area = QtWidgets.QScrollArea()
self.scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(one_btn)
layout.addWidget(self.scroll_area)
self.setLayout(layout)
pass
def one_btn_clicked(self):
self.temp_mark = 1
self.fill_pic_widget()
pass
def fill_pic_widget(self):
'''放置图片'''
# 清空控件
while self.pic_layout.count():
item = self.pic_layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
pass
pass
sc_child_widget = self.scroll_area.takeWidget()
if sc_child_widget is not None:
sc_child_widget.deleteLater()
pre_dir = r'E:/temp005/'
row_i = -2
if self.temp_mark == 1:
self.pic_file_name_list.reverse()
for pic_index,file_name in enumerate(self.pic_file_name_list):
one_check = QtWidgets.QCheckBox(file_name)
pixmap = QtGui.QPixmap(pre_dir + file_name + '.jpeg')
one_piclabel = QtWidgets.QLabel()
one_piclabel.setPixmap(pixmap)
one_piclabel.setScaledContents(True)
col_i = pic_index%4
if col_i == 0:
row_i +=2
print(file_name, row_i, col_i)
self.pic_layout.addWidget(one_check,row_i,col_i,1,1)
self.pic_layout.addWidget(one_piclabel,row_i+1,col_i,1,1)
pass
print('self.pic_layout,',self.pic_layout.count())
one_sc_child_widget = QtWidgets.QWidget()
one_sc_child_widget.setLayout(self.pic_layout)
self.scroll_area.setWidget(one_sc_child_widget)
pass
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
t_win = ExampleWidget()
t_win.show()
sys.exit(app.exec_())
pass
关键点:
QScrollArea中的子控件widget在通过QScrollArea.setWidget(widget)前要把widget的layout设置好放入这样QScrollArea才能正常实现内容;
但这与动态设置控件的需求相悖,动态设置控件意味着要能更新QScrollArea中显示的组件,这就意味着在QScrollArea.setWidget(widget)后,我们还要更改layout,但在setWidget之后更改的layout,QScrollArea是不予理睬的;
所以,每次在更改组件的时候,先把当前QScrollArea中的子控件给删除,layout设置好新的组件后,新创建一个widget, 把layout放入widget, 在把widget通过QScrollArea.setWidget(widget)放入QScrollArea