PDA

View Full Version : Creating children in QtreeWidget with SQL data



sam123
16th June 2016, 11:11
Hello
I have two tables in SQL database and 1st table I have created as a parent In QtreeWidgit using QtreeWidgetItems now I have to add children in parents items respectly, here is the example

table1

Name

Marcus
Andreas
Jacop



table 2

Column 1
Devices

Laptop
Cell Phon
Pc
Laptop
PC
Cell Phon


Column 2
Name

Marcus
Marcus
Marcus
Andreas
Andreas
Jacop




Here table 1 is my parent items and table 2 has two column first is my children items and second I have given for the reference.
Now I have added parent in my QtreeWidget using QtreeWidgetItem but I am not able to add children saperatly.

Main problem I am getting is, Wheneever I add children, All children were added In each parent .

Looking for your advise
Thanks in advance.

anda_skoa
16th June 2016, 11:43
Looks like you forgot to post the code you are using for adding the child items.

Cheers,
_

sam123
16th June 2016, 12:13
Here is the code,



QList<QTreeWidgetItem*>item_list;

QSqlQuery query;
query.prepare("select Name from table1 ");
query.exec();
while(query.next())
{
QTreeWidgetItem * tree_item = new QTreeWidgetItem();
tree_item->setText(0,query.value(0).toString());
item_list.append(tree_item);
ui->treeWidget->addTopLevelItems(item_list); // Adding Tablel 1 as a parents

query.prepare("select Device from table2");
query.exce();
while(query.next())
{
QTreeWidgetItem * child_item = new QTreeWidgetItem();
child_item->setText(0,query.value(0).toString());
item_list.append(child_item);
tree_item->addTopLevelItems(item_list); // Adding Childen accourding to parents referance(not working)
// every chid being adding in every parents.
}
}


My Output:

Marcus

Laptop
Cell Phon
PC
Laptop
PC
Cell Phone

Andreas

Laptop
Cell Phon
PC
Laptop
PC
Cell Phone

Jacop

Laptop
Cell Phon
PC
Laptop
PC
Cell Phone



Expected Output:

Marcus

Laptop
Cell Phon
PC

Andreas

Laptop
PC

Jacop

Cell Phone

anda_skoa
16th June 2016, 12:55
item_list is defined out side of the loop, so the same instance is used in each loop iteration.
You are adding the same list without ever clearing it.

Just don't use that list, you don't need it.

Cheers,
_

sam123
16th June 2016, 13:18
thanks

without list how would I add list of data??

Added after 16 minutes:

will you please tell what changes I have to do for gbetting expected output?

Lesiok
16th June 2016, 13:39
1. For both queries You are using this same QSqlQuery object.
2. In line 13 You should select only equipment belonging to person not all.

sam123
16th June 2016, 14:28
Thank you so much

anda_skoa
16th June 2016, 14:29
without list how would I add list of data??

You don't add a list, you only add the item you just created.
QTreeWidgetItem::addChild() or pass the parent item to the child item's constructor.

The latter also works for top level items if you pass the tree widget to the item's constructor.

Cheers,
_