1

I'm new to this language and I'm working on a project using PyQt.

For those who're familiar with PyQt, I created the .ui file using the Qt Designer, and then tried to load it in python.

I find a really 'weird' thing.

Basically, my UI does not work for the following code:

def main():
   app = QW.QApplication(sys.argv)
   loadUi('my-ui/mainwindow.ui').show()
   sys.exit(app.exec_())

No error message, the window simply doesn't show up.

However, if I change the code to this:

def main():
   app = QW.QApplication(sys.argv)
   w = loadUi('my-ui/mainwindow.ui')
   w.show()
   sys.exit(app.exec_())

It works like magic!

I'm really confused now. What happens in Python during assignment?

You see, the only thing I've changed is adding an assignment.

Larry
  • 858
  • 10
  • 16

1 Answers1

1

What happens during assignment, besides binding an object to a name (w), is, python increases the reference count on an object. That is, the count of references to this object from anywhere else (i.e. another object or a variable).

Objects reaching a reference count of zero are deleted / "garbage collected", since in general there is now way the program code can interact with them anymore.

So what happens in your first variant is, you're creating the widget, but since there's no reference anywhere (in constrast to your second code snipped) it will be destroyed again immediately after the line

loadUi('my-ui/mainwindow.ui').show()

is done.

There's also a (quite) short note on that in the documenation PyQt documenation. And there's of course a lot on python garbage collection in general, see e.g. this question.

Community
  • 1
  • 1
sebastian
  • 9,526
  • 26
  • 54