Massimo
Massimo

Reputation: 966

pyqt. how to add and delete widgets?

i use python 2.7 + qt4.8

how to dynamically change the number of widgets in the window? I need to remove all the widgets and create new ones in the right quantity. testarovaniya made for a simple script:

import sys
from PyQt4 import QtCore, QtGui, uic

class MainForm(QtGui.QDialog):
    def __init__(self):
        super(MainForm, self).__init__()
        uic.loadUi("testQTwindow.ui", self)

        self.connect(self.addBtn, QtCore.SIGNAL("clicked()"), self.addBtnClick)
        self.connect(self.delBtn, QtCore.SIGNAL("clicked()"), self.delBtnClick)

    def addBtnClick(self):
        self.tempBtn = QtGui.QPushButton('button')
        self.gridLayout_2.addWidget(self.tempBtn)

    def delBtnClick(self):
        while True:
            item = self.gridLayout_2.takeAt(0)
            if not item:
                break
            self.gridLayout_2.removeWidget(item.widget())


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

and load this UI: https://yadi.sk/d/jBOmSubYhqbjm

I have two buttons. One for adding buttons to QScrollArea with gridLayout. And the second to remove all the widgets in the QScrollArea. Adding works. I can see how there are new buttons. But when you press the cleaning button does not disappear, and new ones continue to appear over the old ones. The old button can also be pressed, which suggests that they work, and not just the ghosts that are cleaned redrawing window.

I try repaint() and update() functions - but it has no effect...

This is a simple example, but even he is not working. And I do not need to add a button in the future, and whole blocks with a bunch of elements.

How to add and remove widgets dynamically?

Upvotes: 0

Views: 1910

Answers (1)

mdurant
mdurant

Reputation: 28673

This part of the loop should be enough:

    while True:
        item = self.gridLayout_2.takeAt(0)

I suspect you are attempting to delete widgets you already removed, and so prematurely ending your loop. There may have been an error message written somewhere.

Upvotes: 1

Related Questions