سؤال

I'm new to Python and PyQt. What is the best way to keep 4 QtTreeWidgets synchronized so that the items are the same as well as all the attributes of all the items? These widgets appear in different dialog boxes at different times during a session. For a number of reasons, I need to keep as much of the existing code, signals and layout as intact as possible. The Model/View division would be the obvious first place to go, but I don't want to touch any of the methods that are used to access or update the tree. I'm planning to refactor the whole thing in a few months, but I need something quickly to carry me until then.

Since each QTreeWidget is a convenience class, each has its own data. The UI is maintained in Qt Designer and I don't want to keep it that way.

When each dialog is initialized, the tree appears. The application has a singleton class that all dialogs can use to reference its variables/attributes.

In the initialization of each parent dialog, couldn't I check to see if a 'locationTree' attribute exists in the singleton. If not, I would need to populate it with its initial state and have the tree in the dialog use it or a copy of it. Any time the state of the dialog tree is altered in ways that I can trap, I'd like to update the singleton 'locationTree' to mirror the change. Although there's a clone method on a QTreeWidgetItem, I didn't see a corresponding method for the entire QTreeWidget.

How can I accomplish this with the least amount of change to the existing code base and GUI layout?

John

هل كانت مفيدة؟

المحلول

Yes using the MVC facilities is the way to go ...

Even though you are using QTreeWidget you are still working with a class derived from QAbstractItemView therefore the model() and setModel() calls are available. Take a model from one of the widgets that you are creating and then set it in the other widgets. Whenever you change the data in one of the widgets the other widgets will follow suit as they are using the same instance of model.

If you need to maintain the same selection state in all for widgets (which parts of the tree are open or close) that might be a little bit harder but it might actually work by using the same selectionModel selectionModel() and setSelectionModel()

نصائح أخرى

I'm sure you're right that using Model/View is the best approach.

But without an idea of roughly how many items your tree widgets will have, and how frequently they'll be updated, it's hard to weigh up alternative approaches. Also, what version of Qt are you using?

If the number of updates and items are not huge, one approach is to introduce a class that inherits QObject (so it has signals and slots), and make it responsible for keeping all your QTreeWidgets in sync.

By connecting signals and slots for each QTreeWidget to a single other object, you avoid the nightmare of having every tree widget know about every other one.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top