How to clear QVBoxLayout by a Signal?



  • I'm trying to clear QVBoxLayout with self.vbox.takeAt(0), but previous vboxes clog up the QWidget and would not go away. New appear on top of the old ones.

    #! /usr/bin/env python
    from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout, QHBoxLayout
    from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
    import time, random
    
    class Worker(QObject):
    	CLEAR_VBOX = pyqtSignal()
    	intReady = pyqtSignal(int)
    	
    	@pyqtSlot()
    	def procCounter(self):
    		for i in range(1, 100):
    			self.CLEAR_VBOX.emit()
    			self.intReady.emit(i)
    			time.sleep(1)
    
    class Form(QWidget):
    	def __init__(self):
    		super().__init__()
    		
    		self.obj = Worker()
    		self.thread = QThread()
    		self.obj.intReady.connect(self.onIntReady)
    		self.obj.moveToThread(self.thread)
    
    		self.obj.CLEAR_VBOX.connect(self.clearvbox)
    		
    		self.thread.started.connect(self.obj.procCounter)
    		self.thread.start()
    		self.initUI()
    
    
    	def initUI(self):
    		self.vbox = QVBoxLayout()
    		self.setLayout(self.vbox)
    		
    		self.setGeometry(333, 333, 222, 222)
    		self.show()
    		
    	def clearvbox(self):
    		while self.vbox.count():
    			# ~ # break
    			self.vbox.takeAt(0)
    	
    	def onIntReady(self, i):
    		hbox = QHBoxLayout()
    						
    		for ii in range(i):
    			ll = QLabel(str(random.randint(1,9)))		
    			hbox.addWidget(ll)
    
    		self.vbox.addLayout(hbox)
    
    app = QApplication([])
    form = Form()
    app.exec_()
    

  • Lifetime Qt Champion

    Hi,

    Not a direct answer but since you want to show a random sized list of numbers why not use a QListView with a QStringListModel for that ? It would likely be simpler to manage.



  • @SGaist I just simplified the code with Random numbers for demonstration.


  • Moderators

    @porsol I think you need to delete/hide widgets you're removing from the layout as removing them from the layout does not delete or hide them.


  • Qt Champions 2017

    Hi
    takeAt only give you ownership back of the widget.

    However, in most cases where you want to reuse layouts,
    its far easier to use a place holder widget, that has the layout.
    To replace it, you simply delete the placeholder widget
    and allocate a new one (with empty layout) and insert into the layout.



  • def clearvbox(self, L = False):
    	if not L:
    		L = self.vbox
    	if L is not None:
    		while L.count():
    			item = L.takeAt(0)
    			
    			widget = item.widget()
    			
    			if widget is not None:
    				widget.deleteLater()
    			else:
    				self.clearvbox(item.layout())
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.