Reputation: 60
I'm trying to add items inside the QTreeWidget when I add items to my SQLite Database. My Problem is I want to add items as a child to the given other items. Let me show you it inside code. This is my Gui example:
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(213, 327)
Form.setWindowTitle("Form")
self.treeWidget = QtWidgets.QTreeWidget(Form)
self.treeWidget.setGeometry(QtCore.QRect(0, 10, 211, 311))
self.treeWidget.setObjectName("treeWidget")
self.treeWidget.headerItem().setText(0, "Categories")
self.treeWidget.setSortingEnabled(False)
self.printtree()
QtCore.QMetaObject.connectSlotsByName(Form)
def printtree(self):
rn = readsql_Names()
self.treeWidget.setColumnCount(1)
treeItem = QtWidgets.QTreeWidgetItem([rn])
self.treeWidget.addTopLevelItem(treeItem)
def displaytree():
conn = connect_DB() # Connection to the Database
cursor = conn.cursor()
table = cursor.execute(f"SELECT NAME FROM Test")
for item in table.fetchall():
name = str(item[0])
branch_list = QtWidgets.QTreeWidgetItem([name])
treeItem.addChild(branch_list)
# I guess here should be a if statement.
branch_list.addChild(QtWidgets.QTreeWidgetItem(["name"]))
displaytree()
And this is how my SQLite looks like:
def create_testsql(Tree_Table="Test"):
conn = connect_DB()
cursor = conn.cursor()
try:
cursor.execute(f"CREATE TABLE IF NOT EXISTS {Tree_Table} \
(ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \
PARENTID INTEGER, \
NAME TEXT NOT NULL)")
conn.commit()
except:
print("Failure! Creating the TEST Table has failed.")
So I want to check if a Parent Id = ID then it should be showed as a child in the QTreeView. Somehow I have to change printtree function but I don't know how.
That how it should look like when I add item4 when ParentID = ID of item2.
My Tree View Example
Upvotes: 1
Views: 815
Reputation: 60
As @musicamante said it was not possible in a single for loop. So I created a General table where the Item_ID from the Item_Table and the Tree_ID from the Tree_Table was referenced as a Foreign Keys and got an ID which is Unique. Then I run a for loop inside the General table and a if else statement to sort them like:
if item_id == "null":
treeWidget.addTopLevelItem
else:
addChild
Upvotes: 1