[PyQt] newbie: trying to place widgets in a QTreeWidget

Phil Thompson phil at riverbankcomputing.com
Tue Aug 18 16:48:07 BST 2009


On Tue, 18 Aug 2009 08:37:55 -0700 (PDT), blue_riviera
<imre.tuske at gmail.com> wrote:
> Hi,
> 
> I'm new to both Python and PyQt and still learning the ropes (familiar
with
> C++, though). What I'm trying to do is to create a QTreeWidget where some
> items are widgets (say buttons for this example's sake).
> 
> When I try this code (snippet):
> 
> 			cw = QTreeWidget()
> 			cw.setColumnCount(3)
> 
> 			for n in range(3):
> 
> 				i = QTreeWidgetItem(cw) # new row
> 				i.setText(0, "first "+str(n)) # text in first column
> 				i.setText(1, "second") # text in second column
> 
> 				b = QPushButton("push me "+str(n)) # button...
> 				cw.setItemWidget(i, 2, b) # ...goes to the third column
> 
> 
> ...the result is that I'll have 3 rows in my tree widget, but only in the
> third row will have a button (all three will have the texts).
> 
> However when I append the following code to the above snippet:
> 
> 			b1 = QPushButton("push me 0")
> 			cw.setItemWidget(cw.topLevelItem(0), 2, b1) # add button to row 0,
> 			column
> 2
> 
> 			b2 = QPushButton("push me 1")
> 			cw.setItemWidget(cw.topLevelItem(1), 2, b2) # add button to row 1,
> 			column
> 2
> 
> ...which is basically a loop unrolled (but the created buttons are
referred
> to by two separate variables), all two buttons will appear.
> 
> So my suspicion is that it is not a Qt issue, rather a widget ownership
one
> (I suppose when a new button is assigned to the 'b' variable in the loop,
> the previous button loses 'b' as owner and it gets destroyed).
> 
> I suppose I should somehow transfer the button's ownership to (let's say)
> the tree widget once it is created but I don't know how to do that.
Anyone
> can help me out?

It's a bug - it should just work.

As a workaround give the QTreeWidget as the QPushButton parent when you
create the latter...

    b = QPushButton("push me " + str(n), cw)

Phil


More information about the PyQt mailing list