-1

I am trying to display JSON metadata in PyQt6/PySide6 QTreeView. I want to generalize for the case where multiple persistent windows (QtWidgets) pop up if my JSON metadata list has a length greater than 1.

for example:

def openTreeWidget(app, jmd):
    view = QTreeView()
    model = JsonModel()
    view.setModel(model)
    model.load(jmd)
    app.w = view  # app = `self` of a QMainWindow instance
    app.w.show()

for md in jsonMetadataList:
    openTreeWidget(self, md)

where TreeItem and JsonModel are based on: https://doc.qt.io/qtforpython/tutorials/basictutorial/treewidget.html
I stole the app.w idea from: https://www.pythonguis.com/tutorials/pyqt6-creating-multiple-windows/

In the current case, all pop ups (except one) close after momentarily opening. Only the last item in jsonMetadataList remains displayed in a persistent window. I believe that somehow I am not keeping the reference to previous windows and reopening/rewriting data on a single widget. How can I keep the reference?

Also, I am very new to PyQt/PySide so I'm just doing things no matter how ugly they look at the moment. This will, of course, get better with time :);

Ady
  • 9
  • 2
  • I agree that the link goes in great detail to explain how to open multiple windows. And that's how I realised that I am destroying the reference to my windows. However, they also explicitly create references to each window that they expect open (`self.window1 = AnotherWindow(); self.window2 = AnotherWindow()`). So, in a sense, it's more of a Python reference issue (which I had failed implement) rather than that of PyQt/PySide. I managed to do generalise their solution for an arbitrary number of windows in the answer below. Now, I am wondering if there is a *more elegant* way of doing this. – Ady Jun 07 '22 at 09:12

1 Answers1

0

I managed to bodge it up by not destroying the reference. Here's how I did it.

def openTreeWidget(app, jmd):
    """
    app is the parent QWidget (here, a QMainWindow)
    jmd is JSON metadata stored in a string 
    """
    view = QTreeView()
    model = JsonModel()
    view.setModel(model)
    model.load(jmd)
    return view  

# `self` of a QMainWindow instance
self.temp = [None]*len(jsonMetadataList)  # a list storing individual handles for all JSON metadata entries
for ii, md in enumerate(jsonMetadataList):
    self.temp[ii] = openTreeWidget(self, md)  # get the reference for QTreeView and store it in temp[ii]
    self.temp[ii].show()  # show the ii-th metadata in QTreeView

Better ideas are still welcome :)

Ady
  • 9
  • 2