View Single Post
Posts: 3,319 | Thanked: 5,610 times | Joined on Aug 2008 @ Finland
#16
Originally Posted by mikec View Post
Just tried this, and it does not work. you end up appending the same pushbutton into the array, rather than an instance of the qpushbutton. This has got me curious
That's what I get when I don't post a full example just a hint. In python, all those objects are addressed by reference. If I understand correctly what you did, in C terms - you are appending the tempPushbutton *pointer address* to the list, not it's values, so whenever you change it, you changed all the values

I can already hear the question - but then I need to create an array and append all of them... yuck, that's no better than the original ! But before I address that valid concern, let's let's dig a little deeper into the topic of Python-style garbage collection. Take a look at this:

Code:
// C++
col = new QColor();
col = new QColor();

# Python
col = QtGui.QColor()
col = QtGui.QColor()
If you think the two are equivalent, you're wrong The point is that in case of C++, the first created object is still there after the second line, even though it is no longer directly addressable. In Python, however, the events of the second line mean the object will be garbage collected as there are no references left to it ! Now, to curve back to the original problem, we can solve this by increasing the reference count by hierarchical means, by specifying an explicit parent object.

This also explains why you don't get a segfault in your original example - by calling the layout's addWidget before the QPushButton you created a reference that prevents garbage collection. Without this, if you came back to it after the original QPushButton pointer went out of scope (or the reference disappeared for whatever ownership reason), you would get a big fat segfault because (unlike in C++) the underlying object is no longer there. So the alternative solution to local variables (which are ugly if you have many objects) is to specify parents in the constructor, creating the necessary reference to avoid garbage collection (i.e. mylist.append(QPushButton(parent))).

Usually you create enough references inadvertently (like here with addWidget, or QObject voodoo that happens behind the scenes) for garbage collection/ownership not to mess you up, but sooner or later, especially in applications with multiple intertwined classes, you *will* run into segfaults or weirdness because of this. Seems we got into deep water here, but the idea is not to get surprised when you meet your first segfaults and know where to look for trouble spots
__________________
Blogging about mobile linux - The Penguin Moves!
Maintainer of PyQt (see introduction and docs), AppWatch, QuickBrownFox, etc
 

The Following 2 Users Say Thank You to attila77 For This Useful Post: