Solved Iterate through QTreeWidget
-
I have created a QTreeWidget with checkboxes and all that works fine. Now I am trying to iterate through the tree to find out which checkboxes are checked and I am stuck. I have commented out the code in line 49 to 51 which checks the status of the boxes. When I run it I get error "TypeError: 'NoneType' object is not iterable". Any help appreciated. I am a newbie at this so please excuse poor coding.
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QApplication, QWidget
from PyQt5 import QtWidgets
from PyQt5.Qt import Qt
import sysdef tree_checkbox_selected(tw):
iterator = QtWidgets.QTreeWidgetItemIterator(tw, QtWidgets.QTreeWidgetItemIterator.Checked)
while iterator.value():
item = iterator.value()
print (item.text(0))
iterator += 1if name == 'main':
app = 0
if QApplication.instance():
app = QApplication.instance()
else:
app = QApplication(sys.argv)l1 = QTreeWidgetItem(["String A", "String B", "String C"]) l1.setFlags(l1.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) l2 = QTreeWidgetItem(["String AA", "String BB", "String CC"]) for i in range(3): l1_child = QTreeWidgetItem(["Child A" + str(i), "Child B" + str(i), "Child C" + str(i)]) l1_child.setFlags(l1_child.flags() | Qt.ItemIsUserCheckable) l1_child.setCheckState(0, Qt.Unchecked) l1.addChild(l1_child) for j in range(2): l2_child = QTreeWidgetItem(["Child AA" + str(j), "Child BB" + str(j), "Child CC" + str(j)]) l2.addChild(l2_child) for j in range(2): l1_grandchild = QTreeWidgetItem(["GChild XX" + str(j), "GChild YY" + str(j), "GChild ZZ" + str(j)]) l1_child.addChild(l1_grandchild) w = QWidget() w.resize(510, 210) tw = QTreeWidget(w) tw.resize(500, 200) tw.setColumnCount(4) tw.setHeaderLabels(["Column 1", "Column 2", "Column 3","Del"]) tw.addTopLevelItem(l1) tw.addTopLevelItem(l2) column = 0 for item in tree_checkbox_selected(tw): print('State: %s, Text: "%s"' % ( item.checkState(column), item.text(column))) w.show() sys.exit(app.exec_())
-
@ACollins
Hi. Please put all of your code in tags, it makes it much easier to read!Also, when you tell us
in line 49 to 51
, it would help if you, say, put a comment into the code indicating where these lines are. I can't tell!Having said that. I think the content of your
def tree_checkbox_selected(tw):
looks OK (and should beprint()
ing stuff?). Your problem looks to me like where you call it:for item in tree_checkbox_selected(tw):
Your
def tree_checkbox_selected()
function does not return any result, so the error message shows it is treated as returningNone
; and you cannot iterate throughfor item in None:
.You perhaps intend that method to either use
yield
to return items as it iterates along, or just build up alist
of the checked items and return that to the caller?