Python Forum
[PyQt] updating references to data variables across widgets
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] updating references to data variables across widgets
#1
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?
Reply
#2
I like functions. MyWidget should have a function that returns data needed to refresh the widget.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Updating variables in an "after" loop omrot 9 12,589 Jun-13-2018, 08:07 PM
Last Post: omrot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020