Delete last widget from gridlayout

2024/11/20 8:44:19

I have a Grid layout in which I add Qlineedits at runtime.
while pushing the button I want to delete the last qline edit from the gridlaout
Why does this function delete all qlinedits at the same time ?

 def deleate_widgets(self):widgets = (self.main_layout.itemAt(i).widget() for i in range(self.main_layout.count()))for widget in widgets:if isinstance(widget, qtw.QLineEdit):print("linedit: %s  - %s" %(widget.objectName(), widget.text()))widget.deleteLater() # all objects

How to change the code to only delete one widget at a time, preferably the last added widget ?

full code

#!/usr/bin/env python"""
Interface to get the specific  weight of each of the 5 containers
start_measurment_button starts thread /thread_worker
transfer_data button start query and send data to database
"""import sys
import sqlite3from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
from PyQt5 import QtSql as qsqlfrom  PyQt5 import sipclass AddWidget(qtw.QWidget):'''Interface with embedded SQL functions'''# Attribut Signaldef __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)# your code will go hereself.mylist = []# interface# positionqtRectangle = self.frameGeometry()centerPoint = qtw.QDesktopWidget().availableGeometry().center()qtRectangle.moveCenter(centerPoint)self.move(qtRectangle.topLeft())# sizeself.resize(700, 410)# frame titleself.setWindowTitle("add  Widget")# headingheading_label = qtw.QLabel('add Widget')heading_label.setAlignment(qtc.Qt.AlignHCenter | qtc.Qt.AlignTop)# add Buttonself.addwidget_button = qtw.QPushButton("add Widget")self.getlistof_button = qtw.QPushButton("deleate")self.main_layout = qtw.QGridLayout()self.main_layout.addWidget(self.getlistof_button,0,0)self.main_layout.addWidget(self.addwidget_button, 1, 0)self.setLayout(self.main_layout)self.show()# functionalityself.addwidget_button.clicked.connect(self.add_widget)# self.getlistof_button.clicked.connect(self.deleate_widgets_try)def add_widget(self):self.my_lineedit = qtw.QLineEdit()self.mylist.append(self.my_lineedit)self.main_layout.addWidget(self.my_lineedit)def deleate_widgets(self):widgets = (self.main_layout.itemAt(i).widget() for i in range(self.main_layout.count()))for widget in widgets:if isinstance(widget, qtw.QLineEdit):print(widget)# print("linedit: %s  - %s" %(widget.objectName(), widget.text()))# widget.deleteLater() # alle objects# # def deleate_widgets_try(self):#     widgets = (self.main_layout.itemAt(i).widget() for i in range(self.main_layout.count()))#     my_iter = iter(widgets)# #     if isinstance(my_iter, qtw.QLineEdit):#         next(my_iter.deleteLater()) # alle objects)if __name__ == '__main__':app = qtw.QApplication(sys.argv)w = AddWidget()sys.exit(app.exec_())
Answer

Your function removes all widgets because you are cycling through all the widgets, from the first to the last.

Also, there is really no need to go through the whole layout, since you already keep a list of widgets that always appends the last one at the end.

Just pop out the last item from the list. Removing it from the layout shouldn't be necessary, as deleteLater() would take care of it, but that's just for demonstration purposes.

def deleate_widgets(self):# remove the last item from the listlastWidget = self.mylist.pop(-1)self.main_layout.removeWidget(lastWidget)lastWidget.deleteLater()

For the sake of completeness, your function should have done the following:

  1. cycle the widgets through the layout backwards;
  2. break the cycle as soon as the first (as in last) item is found;
def deleate_widgets(self):widgets = [self.main_layout.itemAt(i).widget() for i in range(self.main_layout.count())]# use reversed() to cycle the list backwardsfor widget in reversed(widgets):if isinstance(widget, qtw.QLineEdit):print("linedit: %s  - %s" %(widget.objectName(), widget.text()))widget.deleteLater()# the line edit has been found, exit the cycle with break to avoid# deleting further widgetsbreak

Also, there's really no use in creating instance attributes (self.someobject = ...) for objects that don't need a persistent reference, especially if you are creating those objects repeatedly (which will result in a constant overwrite of that attribute, making it useless) and you already are keeping them in an persistent data model object (usually a list, a tuple, a dictionary) like self.mylist in your case (and that has to be an instance attribute):

def add_widget(self):# no need to create a "self.my_lineedit"my_lineedit = qtw.QLineEdit()self.mylist.append(my_lineedit)self.main_layout.addWidget(my_lineedit)

Having seen your previous questions and comments, I strongly suggest you to better study and experiment with the Python data models, control flows and classes, as they are basic concepts (of Python and programming in general) that must be understood and internalized before attempting to do anything else.

https://en.xdnf.cn/q/118440.html

Related Q&A

Counting unique words

Question:Devise an algorithm and write the Python code to count the number of unique words in a given passage. The paragraph may contain words with special characters such as !, ?, ., , , : and ; and …

Django cant find template dir?

Originally I had just one app in my Django project, the templates consisted of an index.html a detail.html and a layout.html ... the index and detail files extended the layout. They all lived in the sa…

Python Programming Loop

Im doing an assignment where I have to conduct a quiz for different topics. This is my code so far.print("Hello and welcome to Shahaads quiz!") #Introduction name = input("What is your n…

How to fix stale element error without refreshing the page

Trying to get details of Tyres on this page. https://eurawheels.com/fr/catalogue/INFINY-INDIVIDUAL . Each tyre has different FINITIONS. The price and other details are different for each FINITIONS. I w…

Fastest way in numpy to get distance of product of n pairs in array

I have N number of points, for example: A = [2, 3] B = [3, 4] C = [3, 3] . . .And theyre in an array like so: arr = np.array([[2, 3], [3, 4], [3, 3]])I need as output all pairwise distances in BFS (Bre…

How to get argument to ignore part of message

I just wondering how to get the if statement(if 0 < int(message.content)< 153:) to only test part of the message, not the full message.content. Eg: if I put in 1s 100, I want it to test if ONLY t…

how can I limit the access in Flask

I create a project to simulate login my companys website.And put it in my server to let others to use.But the company website has a limit with single ip can only open 2 sessions.So when more than 2 my …

Multiple images numpy array into blocks

I have a numpy array with 1000 RGB images with shape (1000, 90, 90, 3) and I need to work on each image, but sliced in 9 blocks. Ive found many solution for slicing a single image, but how can I obtai…

Python - Transpose columns to rows within data operation and before writing to file

I have developed a public and open source App for Splunk (Nmon performance monitor for Unix and Linux Systems, see https://apps.splunk.com/app/1753/)A master piece of the App is an old perl (recycled, …

Unexpected output while sorting the list of IP address [duplicate]

This question already has answers here:Python .sort() not working as expected(8 answers)Closed last year.I am trying to sort the list of ipaddress from the following list. IPlist= [209.85.238.4, 216.23…