Search code examples
pyqtpysideqwidgetqtreeviewqtreewidget

How to open multiple persistent windows in PyQt?


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 :);


Solution

  • 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 :)