Python Forum
[PyQt] updating references to data variables across widgets - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [PyQt] updating references to data variables across widgets (/thread-32438.html)



updating references to data variables across widgets - Oolongtea - Feb-09-2021

I'd like to know what is the recommended approach to maintain references to an object that is used by multiple widgets.

Let's consider the following code
class MyWidget(QWidget):
    def __init__(self, parent=None, data=None):
        self.data = data

class MyWindow(QMainWindow):
    def __init__(self, parent=None):
        self.data_structure = Datastructure() # Abritrary mutable data structure
        self.widget1 = MyWidget(self, data=self.datastructure)
        self.widget2 = MyWidget(self, data=self.datastructure)
        ...

    def load_new_data(path):
        self.data_structure = create_new_data_structure_from_file(path)

Naturally, any changes made in place to data_structure will be reflected in widget1 and widget2. So far so good
Now if I replace the data_structure with a new instance, let's say for example after loading a file, I will lose the coupling with the widgets because they are still referencing the old instance.
I've thought about a few approaches
  • Maintain the reference by putting the data structure inside a mutable container (a list for example)
  • Create a method in Datastructure to clear/copy data from a new instance.. which seems a huge hassle if the data structure is complex, and the new instance already has all the data I need anyway
  • Create methods in the widgets to update the reference to the new instances. Reflecting the changes down the line could become cumbersome if the widgets have children and so on...
  • Destroy old widgets and replace with new ones. Again, this should work fine if limited to a few descendants, maybe not if I have to regenerate a big chunk of my interface as a chain reaction

Or something else entirely?


RE: updating references to data variables across widgets - deanhystad - Feb-09-2021

I like functions. MyWidget should have a function that returns data needed to refresh the widget.