问:如何在布局中动态添加和删除小部件?

时间:2016-12-08 19:00:05

标签: qt user-interface pyqt qwidget

def add_ranges(self):
    self.ranges_layout = QtGui.QHBoxLayout()                            # setup the ranges_layout, it will be a child of all_ranges_layout
    self.min_label = QtGui.QLabel(self.normalization)                   # setup the min label
    self.max_label = QtGui.QLabel(self.normalization)                   # setup the max label
    self.min_lineEdit = QtGui.QLineEdit(self.normalization)             # setup the min lineEdit
    self.max_lineEdit = QtGui.QLineEdit(self.normalization)             # setup the max lineEdit
    self.all_ranges_layout.addLayout(self.ranges_layout)                # make ranges_layout a child of all_ranges_layout
    self.ranges_layout.addWidget(self.min_label)                        # apply the min label to the widget
    self.ranges_layout.addWidget(self.min_lineEdit)                     # apply the min lineEdit to the widget
    self.ranges_layout.addWidget(self.max_label)                        # apply the max label
    self.ranges_layout.addWidget(self.max_lineEdit)                     # apply the max lineEdit
    self.min_label.setText(_translate("MainWindow", "Min", None))       # set the text of the min label
    self.max_label.setText(_translate("MainWindow", "Max", None))       # set the text of the max label

    self.min_lineEdits.append(self.min_lineEdit)                        # set up an array of lineEdits
    self.max_lineEdits.append(self.max_lineEdit)                        #

def del_ranges(self):
    self.ranges_layout.removeWidget(self.min_label)                     # remove the min label to the widget
    self.ranges_layout.removeWidget(self.min_lineEdit)                  # remove the min lineEdit to the widget
    self.ranges_layout.removeWidget(self.max_label)                     # remove the max label
    self.ranges_layout.removeWidget(self.max_lineEdit)                  # remove the max lineEdit
    del self.min_lineEdits[-1]                                          # delete last element in list
    del self.max_lineEdits[-1]                                          # delete last element in list

enter image description here 单击"添加范围",将显示两个新框,供用户添加数据。

enter image description here 单击"删除范围",除按钮在视觉上向上移动外没有任何反应。这告诉我该函数正在工作(排序)并且正在删除布局,但不是lineEdits和标签。

这是我设计的程序中的两个功能。我希望通过按下按钮添加和删除小部件。我尝试使用deleteLater()但是,这个功能也落入了同一个坑;实际上并没有删除lineEdits和标签。在删除之前是否存在断开连接的问题?

1 个答案:

答案 0 :(得分:2)

使用此方法。它将迭代地遍历布局和deleteLater()特定布局中的每个小部件。在这种情况下self.all_ranges_layout

def del_ranges(self):
    to_delete = self.all_ranges_layout.takeAt(self.all_ranges_layout.count() - 1)
    if to_delete is not None:
        while to_delete.count():
            item = to_delete.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                pass

获取n-1索引的布局项
如果有要删除的对象,请继续
虽然计数不是0
获取第0个索引的布局项
在这个位置获取小部件
如果此小部件中有对象
删除此小部件