Issue
I have a QGridLayout
and need to remove all of its buttons then re-create them.
I've tried looping over the layout using count()
followed by takeAt()
to delete the returned LayoutItem
's widget. For some reason, however, I am only getting half of the widgets: the other LayoutItem
s don't have widgets. This is very odd, as I can see them.
Here is my current simplified code.
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class GridView(QWidget):
def __init__(self, parent=None):
super(GridView, self).__init__(parent)
self.grid = QGridLayout(self)
def setButtons(self):
self.clearPage()
for i in xrange(10):
btn = QPushButton(str(i))
self.grid.addWidget(btn, i / 2, i % 2)
def clearPage(self):
for i in xrange(self.grid.count()):
print i
layoutItem = self.grid.takeAt(i)
# the following errors out after the fifth iteration as layoutItem.widget() returns None
print layoutItem.widget()
layoutItem.widget().deleteLater()
app = QApplication(sys.argv)
mainWindow = QWidget()
layout = QVBoxLayout()
mainWindow.setLayout(layout)
btn = QPushButton('test')
v = GridView()
btn.clicked.connect(v.setButtons)
layout.addWidget(v)
layout.addWidget(btn)
mainWindow.show()
sys.exit(app.exec_())
Solution
Try using
self.grid.takeAt( 0 )
instead of:
self.grid.takeAt(i)
In your code, you takeAt( 0 ) in the first iteration. This internally makes the old #1 being the new #0, the old #2 being the new #1 and so on.
Then in your next iteration you takeAt( 1 ), which in fact is the old #2. That way the old #1 (which is #0 now) will not be deleted.
Answered By - Tim Meyer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.