سؤال

I was hoping some one could explain to me the difference and reason behind why I keep coming across two different methods for which people place buttons into the widget? I sometimes see

button = Button('Button', self)

or

self.spinner = QtGui.QSpinBox()

I just want to know whats the difference, is one more beneficial than the other? When to use which in what scenarios and why? Does the position of 'self' affect this in the widget some how?

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

المحلول

Assuming you only care about PyQt and PySide…

There are two different places that self appears in your examples, which mean very different things.


First, as an argument to the constructor:

Every widget's constructor has a parent parameter, with a default value of None.

There are three reasons to leave out the parent:

  • You're going to assign the widget to a layout or other parent after creation.
  • You're creating a top-level window.
  • You're creating a special-purpose widget like QDesktopWidget.

If none of these are true, you need to pass a parent. If self is a widget, and the thing you're creating is a child of that widget, you will pass self as the parent.

Here's an example of the first alternative:

self.spinner = QtGui.QSpinBox()
hbox = Qt.QHBoxLayout()
hbox.addWidget(self.spinner)
self.addLayout(hbox)

We can't pass a parent to QSpinBox at construction time because its parent doesn't exist yet. So, we leave it off, and addWidget it to a layout object later.

This is all explained early in most tutorials for PySide or PyQt, like First programs in PySide and Layout management in PySide.


Meanwhile, one of your examples stores the widget in self.spinner, making it an instance attribute on self, which means we can refer to it later. For example, if some other method (like the signal handler for a button) wants to adjust the spinner's value, it can access it as self.spinner.

If you will never need to refer to the child widget in your code after the current function, you don't need to store it.

This part is explained in the Classes chapter in the Python tutorial.

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