Issue
In PyQt5 I am dynamically adding QPushButtons, is there a way to delete them based on some label value. I am dynamically adding buttons in the following manner:
for i in range(0, len(self.all_saved)):
self.button = QPushButton("X", self)
self.button.setStyleSheet("background-color: red")
self.button.resize(20, 20)
self.button.clicked.connect(lambda ch, i=i: self.future(i))
self.button.move(self.all_rect[i][0], self.all_rect[i][1])
self.button.show()
Once the user clicks the button 'X' it should delete itself, thats basically all I am trying to do here, as to why I cant use QVBoxLayout is because all the buttons would be placed on different x,y co ordinates please let me know if you have any suggestions?
I know we can do this easily with QVBoxLayout or QHBoxLayout but is there a way to do it directly on QtWidgets.QWidget
Solution
You just have to invoke the deleteLater()
method that will delete the object and notify(using destroyed signal) the layout that the widget was deleted. Note: Don't use self.button as it is useless.
for i in range(0, len(self.all_saved)):
button = QPushButton("X", self)
button.setStyleSheet("background-color: red")
button.resize(20, 20)
button.clicked.connect(button.deleteLater)
button.move(self.all_rect[i][0], self.all_rect[i][1])
button.show()
If you want to delete certain buttons based on some condition then you must use the sender () method to get the button and call deleteLater:
button.clicked.connect(self.handle_clicked)
def handle_clicked(self):
button = self.sender()
if some_condition:
button.deleteLater()
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.