QString sSql = QString("SELECT id, name FROM elements WHERE parent_id IS NULL OR parent_id=0 ORDER BY name ASC"); QSqlQuery parentsQuery; if(!parentsQuery.exec(sSql)) return; while(parentsQuery.next()) { int parentId = parentsQuery.value(0).toInt(); QString parentName = parentsQuery.value(1).toString(); QTreeWidgetItem* parentItem = new QTreeWidgetItem(someTreeWidget, QStringList(parentName)); parentItem->setData(0, Qt::UserRole + 1, parentId); someTreeWidget->addTopLevelItem(parentItem); // вероятно, можно удалить, т.к. в теории QTreeWidgetItem(someTreeWidget, ...) сделает ноду топовой { sSql = QString("SELECT id, name FROM elements WHERE parent_id=%1 ORDER BY name ASC").arg(parentId); QSqlQuery childrenQuery; if(childrenQuery.exec(sSql)) { while(childrenQuery.next()) { int childId = childrenQuery.value(0).toInt(); QString childName = childrenQuery.value(1).toString(); QTreeWidgetItem* childItem = new QTreeWidgetItem(parentItem, QStringList(childName)); childItem->setData(0, Qt::UserRole + 1, childId); } } } }