如何让QScrollArea适配内部动态变化的QGridLayout正常显示?
在QScrollArea中动态调整QGridLayout内QCheckBox数量时滚动条不显示的问题
我需要在QScrollArea里用QGridLayout创建多个QCheckBox,并且支持修改复选框的数量。目前遇到的问题是,当增加复选框数量时,这些控件会被强行压缩在QScrollArea的可视范围内,右侧并没有自动出现滚动条来显示超出的内容。
示例代码如下:
import sys import numpy as np from PyQt6.QtGui import * from PyQt6.QtCore import * from PyQt6.QtWidgets import * class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__() self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self.mainHBOX = QVBoxLayout() layout_toApply = QGroupBox('Checkboxes') self.layout_toApply_V = QVBoxLayout() self.grid_toApply_V = QGridLayout() self.Stimulation_NbSources_Edit =QLineEdit('100') self.Stimulation_NbSources_PB =QPushButton('Apply') self.ChangeNBSource_fun() layout_toApply.setLayout(self.layout_toApply_V) self.layout_toApply_V.addLayout(self.grid_toApply_V) self.layout_toApply_V.addWidget(self.Stimulation_NbSources_Edit) self.layout_toApply_V.addWidget(self.Stimulation_NbSources_PB) self.mainHBOX.addWidget(layout_toApply) self.mainHBOX_W = QWidget() self.mainHBOX_W.setLayout(self.mainHBOX) self.widgetparam_w = QWidget() layout_toApplyparam_w = QHBoxLayout() self.widgetparam_w.setLayout(layout_toApplyparam_w) self.scrolltoparam_w = QScrollArea(self.widgetparam_w) self.scrolltoparam_w.setWidget(self.mainHBOX_W) self.mainlay = QHBoxLayout() self.mainlay.addWidget(self.scrolltoparam_w) self.centralWidget.setLayout(self.mainlay) self.centralWidget.setFixedSize(QSize(500,500)) self.Stimulation_NbSources_PB.clicked.connect(self.ChangeNBSource_fun) def ChangeNBSource_fun(self): for i in reversed(range(self.grid_toApply_V.count())): widgetToRemove = self.grid_toApply_V.itemAt(i).widget() widgetToRemove.setParent(None) widgetToRemove.deleteLater() N = int(self.Stimulation_NbSources_Edit.text()) nb_column = 10 nb_line = int(np.ceil(N / nb_column)) self.Apply_to_pop = [] for l in np.arange(nb_line): for c in np.arange(nb_column): idx = (l) * nb_column + c + 1 if idx <= N: CB = QCheckBox(str(idx - 1)) CB.setFixedWidth(int(30)) CB.setChecked(False) self.grid_toApply_V.addWidget(CB, l, c) self.Apply_to_pop.append(CB) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
初始运行效果:
复选框数量翻倍后效果:
内容的提问来源于stack exchange,提问作者ymmx
相关产品推荐
相关产品推荐

