Summary:
I am trying to make a pyqt5 UI that reads in a dictionary from a json file and dynamically creates an editable form. I would then like to be able to change the json file and have my form update.
What I've tried:
I think the simplest solution would be just to somehow destroy the ui and re-initialize the ui with a new dictionary, I have tried to understand this post, but I am not to sure how to modify this answer to reboot and then instantiate a new UI class with a new dictionary?
I have also read a few posts like this post which I think I can use to first delete all my widgets, then delete my layout and then re add new widgets and layouts from a new dictionary, but I wonder if this is just over complicating the problem?
Some example code:
import sys
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QFormLayout
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QApplication
class JsonEditor(QMainWindow):
def __init__(self, dictionary):
super().__init__()
self.dictionary = dictionary
self.setWindowTitle("Main Window")
self.setGeometry(200, 200, 800, 100)
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.main_layout = QVBoxLayout(self.main_widget)
self.createDynamicForm()
self.createUpdateButton()
def createDynamicForm(self):
self.dynamiclayout = QFormLayout()
self.dynamic_dictionary = {}
for key, value in self.dictionary.items():
self.dynamic_dictionary[key] = QLineEdit(value)
self.dynamiclayout.addRow(key, self.dynamic_dictionary[key])
self.main_layout.addLayout(self.dynamiclayout)
def createUpdateButton(self):
self.update_button = QPushButton('update')
self.main_layout.addWidget(self.update_button)
self.update_button.clicked.connect(self.updateDictionary)
def updateDictionary(self):
dictionary2 = {}
dictionary2['foo2'] = 'foo_string2'
dictionary2['bar2'] = 'bar_string2'
dictionary2['foo_bar'] = 'foo_bar_string2'
self.dictionary = dictionary2
dictionary1 = {}
dictionary1['foo'] = 'foo_string'
dictionary1['bar'] = 'bar_string'
if __name__ == "__main__":
test_app = QApplication(sys.argv)
MainWindow = JsonEditor(dictionary1)
MainWindow.show()
sys.exit(test_app.exec_())
I suppose I am at the stage of learning where I probably don't know exactly the right questions to ask or how to describe terminology correctly, so I hope this makes sense.