所以我正在构建管理一堆自定义滑块小部件的程序。目前,我有一个slider_container(类),它包含一个滑块对象列表(类)。然后将这些滑块对象插入主窗口的布局中。这一直运作良好,而我只是添加和移动滑块的位置上下。但是当我尝试删除滑块时,一切都变坏了。当操作滑块列表(添加,移动或删除滑块)时,在主窗口中调用清除和重建功能,如下所示。
def clear_layout(self, layout):
print "Cleared Layout..."
while layout.count() > 0:
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
def rebuild_slider_display(self):
""" Delete the old sliders, then add all the new sliders """
self.clear_layout(self.slider_layout)
print "Rebuild layout..."
print len(self._widgets.widgets)
for i, widget in enumerate(self._widgets.widgets):
print widget.slider_name, " ", i
self.slider_layout.insertWidget(i, widget)
print "Layout widget count: ", self.slider_layout.count()
目前我在这行“self.slider_layout.insertWidget(i,widget)”中遇到此错误
RuntimeError: wrapped C/C++ object of type SliderWidget has been deleted
我的预感是将实际的小部件存储在小部件容器中是不好的形式。我认为当我deleteLater()一个小部件时发生的事情是,它不仅仅是从列表中删除一个小部件,它实际上删除了存储在小部件容器本身中的小部件类。
希望能够清楚地解释这一点,感谢您的帮助。
编辑:
这是小部件类:
class SliderWidget(QWidget, ui_slider_widget.Ui_SliderWidget):
""" Create a new slider. """
def __init__(self, name, slider_type, digits, minimum, maximum, value, index, parent=None):
super(SliderWidget, self).__init__(parent)
self.setupUi(self)
self.slider_name = QString(name)
self.expression = None
self.accuracy_type = int(slider_type)
self.accuracy_digits = int(digits)
self.domain_min = minimum
self.domain_max = maximum
self.domain_range = abs(maximum - minimum)
self.numeric_value = value
self.index = index
#self.name.setObjectName(_fromUtf8(slider.name))
self.update_slider_values()
self.h_slider.valueChanged.connect(lambda: self.update_spinbox())
self.spinbox.valueChanged.connect(lambda: self.update_hslider())
self.edit.clicked.connect(lambda: self.edit_slider())
# A unique has for the slider.
def __hash__(self):
return super(Slider, self).__hash__()
# How to compare if this slider is less than another slider.
def __lt__(self, other):
r = QString.localAware.Compare(self.name.toLower(), other.name.toLower())
return True if r < 0 else False
# How to compare if one slider is equal to another slider.
def __eq__(self, other):
return 0 == QString.localAwareCompare(self.name.toLower(), other.name.toLower())
这里是widget组件中实际创建的小部件:
def add_slider(self, params=None):
if params:
new_widget = SliderWidget(params['name'], params['slider_type'], params['digits'], params['minimum'],
params['maximum'], params['value'], params['index'])
else:
new_widget = SliderWidget('Slider_'+str(self.count()+1), 1, 0, 0, 50, 0, self.count())
#new_widget.h_slider.valueChanged.connect(self.auto_save)
#new_widget.h_slider.sliderReleased.connect(self.slider_released_save)
new_widget.move_up.clicked.connect(lambda: self.move_widget_up(new_widget.index))
new_widget.move_down.clicked.connect(lambda: self.move_widget_down(new_widget.index))
self.widgets.append(new_widget)
感谢您的帮助!
答案 0 :(得分:0)
我遇到的问题是我清除布局的方式。如下所示,从底部到顶部清除布局非常重要。
for i in reversed(range(layout.count())):
layout.itemAt(i).widget().setParent(None)