Ryan
Ryan

Reputation: 289

Layout not adding correctly, seems that its not erasing previous widgets

After every click on a "Add Item..." button, I want a row(label, button) to be appended to the layout (below that same button).

So, it should add one row per click.

Problem is it adds the following:

1st click: 1 row added (total item rows = 1) (correct)

2nd click: 2 rows added (total item rows = 3) (should be 2)

3rd click: 3 rows added (total item rows = 6) (should be 3)

Here's the relevant code:

from PySide import QtCore
from PySide import QtGui

import sys

class Form(QtGui.QDialog):

    items = []
    def __init__(self, parent = None):
        super(Form, self).__init__(parent)

        self.btn = QtGui.QPushButton("Add Item...")
        self.btn.clicked.connect(self.item_toggle)

        self.layout = self.initial_view()
        self.setLayout(self.layout)

    def item_toggle(self, add = True):
        layout = self.layout

        if add:
            string = ("25468 5263.35 54246") #####random text
            self.items.append(string)

        for item in self.items:
            rem_btn = QtGui.QPushButton("X")
            rem_btn.clicked.connect(self.remove_item)
            layout.addRow(item, rem_btn)

        self.setLayout(layout)

    def remove_item(self, ):
        #self.items.pop() #something to delete that item
        self.add_item("False")  #redraw items part

    def initial_view(self, ):
        layout = QtGui.QFormLayout()
        #adding to layout
        layout.addRow(self.btn)
        return layout

app = QtGui.QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

I figure its not erasing the previous widgets, but I can't quiet figure it out. Also, a way to to remove the items(remove_item function), would also help me out.

I hope I explained well and you get what I'm trying to do...

Any help will be appreciated. Thanks in advance

Upvotes: 0

Views: 109

Answers (1)

Liz
Liz

Reputation: 8958

To prevent adding additional items to your list just remove the for loop and just do the following:

rem_btn = QtGui.QPushButton("X")
rem_btn.clicked.connect(self.remove_item)
layout.addRow(string, rem_btn)

What you have to know about the addRow call, is that this add your QPushButton in the second column, and auto-creates a QLabel for the first column. So when you want to remove the row, you will have to remove both the button and the label.

Now about the remove. I guess the easiest way to start would be to find out which button is asking to be removed.

 sending_button = self.sender() 

At this point you will need to get access to the QLabel. Luckily there is a call on the layout called labelForField which will return the QLabel associated with your QPushButton

labelWidget = self.layout.labelForField(sending_button)

Then to remove the actual widgets

sending_button.deleteLater()
if labelWidget:
   labelWidget.deleteLater()

Upvotes: 1

Related Questions