25

I recently decided to write my first app with Python and PySide. But I have a problem and hope you guys can help.

Python keeps raising exceptions that the "Internal C++ Object" is deleted. From my limited experience with Python I figure that my object is going out of scope and being deleted by Python's Garbage Collector.

So how would I go about designing a multi-page application in Python with PySide. And being able to keep my QWidgets so I can show the page again.

Thanks for your time.

Update (Code)

instancing = None
def instance():
   global instancing
   if instancing == None:
      instancing = WPZKernel()
   return instancing

class WPZKernel:
    win = None
    mainscreen = None

    def mainwindow(self):
        if self.win == None:
          self.win = GMKMainWindow(self)
        return self.win

    def main_panel(self):
        if self.mainscreen == None:
           self.mainscreen = GMKMainScreen(self.mainwindow())
        return self.mainscreen

I would then normally access the mainpanel by calling:

import kernel
kernel.instance().main_panel()

So am I going about this the wrong way?

Johann du Toit
  • 2,609
  • 2
  • 16
  • 31

2 Answers2

22

After some searching and hair pulling, I found the solution. I was showing all the pages by setting them as the central widget, and when reading the QMainWindow documentation I found that my widget basically gets deleted by qt as stated:

Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time.

So to develop a Multi-Page application rather take a look at QStackedWidget.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Johann du Toit
  • 2,609
  • 2
  • 16
  • 31
16

See here: PySide Pitfalls.

If a QObject falls out of scope in Python, it will get deleted. You have to take care of keeping a reference to the object:

  • Store it as an attribute of an object you keep around, e.g. self.window = QMainWindow()
  • Pass a parent QObject to the object’s constructor, so it gets owned by the parent
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
  • Does the object I store it as a property have to be a QObject or QWidget? – Johann du Toit Mar 17 '11 at 12:57
  • No, any Python object will do, as long as the object does not go out of scope. – Janne Karila Mar 17 '11 at 14:20
  • Ok but where my instance object go out of scope? I'm starting the app by calling kernel.instance().bootstrap() and all the other widgets call kernel.instance().mainwindow() if they need the mainwindow or other widgets. – Johann du Toit Mar 17 '11 at 14:22
  • Hmm... I only just now looked at the code, and it would seem OK, `instancing` does not go out of scope. – Janne Karila Mar 17 '11 at 14:27
  • I'm running into the issue in the original question, but it's difficult to reproduce, is there some way that i can trigger it manually? – sunyata Jun 22 '20 at 16:18