So I've got a pyqt5 GUI that generates checkboxes based on the titles of JSON files that are saved in a directory. My next step is making it so that when the users checks a box, it deletes the checkbox, and then the JSON file.
Currently I generate the checkboxes as follows:
for x in self.list:
layout.addWidget(QCheckBox(x),row,0)
row+=1
Since I have not assigned each checkbox to an object, how would I go about checking the state of each box, and then assigning it an action?
Since I'm learning to discuss what I was thinking:
I was hoping I could use Signals to detect when a signal is transmitted from the overall widget, and then slot that with a function that deletes any file in the directory sharing the name of the object that generated the signal.
Is there a better approach to generate the checkboxes as well?
To store the widget so later you can access them create some container, List will do perfectly:
self.checkboxes = []
...
checkbox = QCheckBox("Iam checkbox number: {}".format(len(self.checkboxes))) #Create checkbox
self.vbox.addWidget(checkbox) #Add it to layout
self.checkboxes.append(checkbox) #Store it for later use in List
For deleting them you can use the .deleteAfter() method:
self.checkboxes[-1].deleteLater() #[-1] gives us the last element and .deleteLater() gets rid of the widget GUI wise.
self.checkboxes.pop() #Then we just remove the last element from the list so it doesn't take space
This is the whole working example:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QCheckBox, QVBoxLayout
class App(QWidget):
def __init__(self):
super().__init__()
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle("My app")
self.vbox = QVBoxLayout()
self.vbox.addStretch(1)
cr_button = QPushButton('Press to add widgets')
cr_button.clicked.connect(self.create)
del_button = QPushButton('Press to delete widgets')
del_button.clicked.connect(self.delete)
self.vbox.addWidget(cr_button)
self.vbox.addWidget(del_button)
self.checkboxes = []
self.setLayout(self.vbox)
self.show()
def create(self):
checkbox = QCheckBox("Iam checkbox number: {}".format(len(self.checkboxes)))
self.vbox.addWidget(checkbox)
self.checkboxes.append(checkbox)
self.show()
def delete(self):
self.checkboxes[-1].deleteLater()
self.checkboxes.pop()
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With