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.<br>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.<br>
<br>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.<br><br><br><br><br><br>from PyQt4.QtCore import *<br>from PyQt4.QtGui import *<br>
<br>class MyItem(QTreeWidgetItem):<br> def __init__(self, parent, text1=None, text2=None):<br> QTreeWidgetItem.__init__(self, parent)<br> <br> self.text1 = text1<br> self.text2 = text2<br> self.setText(0, self.text1)<br>
self.setText(1, self.text2)<br> <br>class MyTree(QTreeWidget):<br> def __init__(self, parent):<br> QTreeWidget.__init__(self, parent)<br> self.itemList = []<br> self.setColumnCount(3)<br>
<br> for i in range(5):<br> item = MyItem(self, text1='Initial Item', text2='Item #: ' + str(i))<br> <br> # Always inserting at the top of the list<br> self.insertTopLevelItem(0, item)<br>
self.itemList.append(item)<br> print 'Item : ', str(item.text(0)) + ' : ' + str(item.text(1)), ' index: ', str(i) <br> <br>class MyClass(QMainWindow):<br> def __init__(self):<br>
QMainWindow.__init__(self)<br> self.resize(600,400)<br> <br> # Central Widget<br> self.layoutWidget = QWidget(self)<br> self.setCentralWidget(self.layoutWidget)<br> <br> # Button<br>
self.btn = QPushButton(self.layoutWidget)<br> self.btn.setText('ReInsert')<br> self.btn.setGeometry(QRect(0,0,60,40))<br> self.btn.setMinimumSize(QSize(60, 40))<br> self.btn.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))<br>
# Tree<br> self.tree = MyTree(self.layoutWidget)<br> # Layout<br> self.lv_Main = QVBoxLayout(self.layoutWidget)<br> self.lv_Main.addWidget(self.btn)<br> self.lv_Main.addWidget(self.tree)<br>
# Connections<br> self.connect(self.btn, SIGNAL('clicked()'), self.reinsertItems)<br> <br> def reinsertItems(self):<br> tempItemList = []<br> <br> for i in range(self.tree.topLevelItemCount()):<br>
item = self.tree.takeTopLevelItem(i)<br> tempItemList.append(item)<br> <br> # Just to print out the order of the list<br> for item in tempItemList:<br> print 'tempItemList Item index: ', item.text(1)<br>
<br> print "All items removed, check Tree's Item count: ", self.tree.topLevelItemCount()<br> <br> #for i in range(5):<br> for item in tempItemList:<br> self.tree.insertTopLevelItem(0, item)<br>
print 'Item : ', str(item.text(0)) + ' : ' + str(item.text(1))<br> <br> <br>app = QApplication([])<br>form = MyClass()<br>form.show()<br>app.exec_()<br>