2

I'm new here, and I'm French, so please forgive my English.

One of my functions creates some buttons with given labels, from a list of tags, when I select a cell from a QTableView. But when I select another cell, sometimes the list of the tags is empty (and must be). So I'd like to clear my layout of the old buttons, to display nothing if there is no tag in the list. But here the code:

def clearLayout(self, layout):
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                self.clearLayout(item.layout())



def getInfos(self, element):

    """Slot qui récupère les infos d'une vidéo quand la cell
    correspondante est sélectionnée"""

    self.tags = liste.displayTag(self.modele.record(element.row()).value('id'))

    self.vbox_tags = QtGui.QVBoxLayout()

    if self.tags != None:
        self.liste_boutons = list()
        for indice, tag in enumerate(self.tags):
            self.liste_boutons.append(QtGui.QPushButton(tag))

            #Utilisation de la fonction partial trouvée ici:
            #http://stackoverflow.com/questions/4578861/connecting-slots-and-signals-in-pyqt4-in-a-loop
            self.liste_boutons[indice].clicked.connect(partial(self.displayVidsWithTag, tag))
            self.vbox_tags.addWidget(self.liste_boutons[indice])

        #On aligne les boutons des tags en haut
        self.vbox_tags.setAlignment(QtCore.Qt.AlignTop)
        self.onglet_tags.setLayout(self.vbox_tags)
    else:
        self.clearLayout(self.vbox_tags)

the clearLayout method doesn't undisplay my buttons. Could you help to solve my problem please?

Sincerely.

JPFrancoia
  • 4,866
  • 10
  • 43
  • 73

1 Answers1

3

You are overwriting your previous layout before your clearLayout ever gets a chance to see it:

# previous self.vbox_tags layout goes bye-bye
self.vbox_tags = QtGui.QVBoxLayout()

if self.tags != None:
    ...
else:
    # clearing a new empty one
    self.clearLayout(self.vbox_tags)

This means that you are basically clearing an empty new layout if self.tags != None. I am not sure what your exact usage is, that you want to always create a new layout... but at least save a reference first:

old_layout = self.vbox_tags
self.vbox_tags = QtGui.QVBoxLayout()
...
self.clearLayout(old_layout)

You would probably want to destroy the old layout object as well if you are always creating a new one: old_layout.deleteLater()

jdi
  • 90,542
  • 19
  • 167
  • 203
  • Nice one man. I feel stupid... I juste moved the declaration of the QVBoxLayout in my initUI method, and everything works. Thanks a lot. – JPFrancoia Aug 08 '12 at 18:21
  • Glad to help. Make sure to hit the checkmark to close the question if this solved your problem! – jdi Aug 08 '12 at 18:41