[PyQt] QTreeWidgetItem - how to properly delete so tree.insertTopLevelItem(0, treeWidgetItem) works
Taylor Carrasco
crackerbunny at gmail.com
Fri Apr 2 05:52:23 BST 2010
My question is simple, I want to take the QTreeWidgetItems out of a tree,
and reinsert them in a specific order. So far with custom classes I've been
unable to succeed.
I tried below to build a simple example of my issue but it errors out when I
hit the "ReInsert" button, perhaps due to what I'm doing wrong, perhaps for
another reason I'm overlooking.
Unfortunately I can't figure out what I'm doing wrong on the "ReInserting"
of the items into the tree, but maybe it has to do with my question.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyItem(QTreeWidgetItem):
def __init__(self, parent, text1=None, text2=None):
QTreeWidgetItem.__init__(self, parent)
self.text1 = text1
self.text2 = text2
self.setText(0, self.text1)
self.setText(1, self.text2)
class MyTree(QTreeWidget):
def __init__(self, parent):
QTreeWidget.__init__(self, parent)
self.itemList = []
self.setColumnCount(3)
for i in range(5):
item = MyItem(self, text1='Initial Item', text2='Item #: ' +
str(i))
# Always inserting at the top of the list
self.insertTopLevelItem(0, item)
self.itemList.append(item)
print 'Item : ', str(item.text(0)) + ' : ' + str(item.text(1)),
' index: ', str(i)
class MyClass(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.resize(600,400)
# Central Widget
self.layoutWidget = QWidget(self)
self.setCentralWidget(self.layoutWidget)
# Button
self.btn = QPushButton(self.layoutWidget)
self.btn.setText('ReInsert')
self.btn.setGeometry(QRect(0,0,60,40))
self.btn.setMinimumSize(QSize(60, 40))
self.btn.setSizePolicy(QSizePolicy(QSizePolicy.Fixed,
QSizePolicy.Fixed))
# Tree
self.tree = MyTree(self.layoutWidget)
# Layout
self.lv_Main = QVBoxLayout(self.layoutWidget)
self.lv_Main.addWidget(self.btn)
self.lv_Main.addWidget(self.tree)
# Connections
self.connect(self.btn, SIGNAL('clicked()'), self.reinsertItems)
def reinsertItems(self):
tempItemList = []
for i in range(self.tree.topLevelItemCount()):
item = self.tree.takeTopLevelItem(i)
tempItemList.append(item)
# Just to print out the order of the list
for item in tempItemList:
print 'tempItemList Item index: ', item.text(1)
print "All items removed, check Tree's Item count: ",
self.tree.topLevelItemCount()
#for i in range(5):
for item in tempItemList:
self.tree.insertTopLevelItem(0, item)
print 'Item : ', str(item.text(0)) + ' : ' + str(item.text(1))
app = QApplication([])
form = MyClass()
form.show()
app.exec_()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20100402/f4374916/attachment-0001.html>
More information about the PyQt
mailing list