Using Qt TreeView to Render Grouped Entries

In this example, we will see how a list of contacts/buddies under some groups can be shown by Qt tree view.
At first retrieve the list of groups. Then initialize the model.

 
QList<QStandardItem*> groupList;
    QStandardItem* groupItem;
 
 
    foreach (QString group, groupStrList) {
        groupItem = new QStandardItem(group);
        groupItem->setAccessibleText(group);
        groupList.append(groupItem);
        treeModel->setItem(groupStrList.indexOf(group, 0), 0, groupItem);
        treeModel->setItem(groupStrList.indexOf(group, 0), 1, new QStandardItem(""));
        treeModel->setItem(groupStrList.indexOf(group, 0), 2, new QStandardItem(""));
        treeModel->setItem(groupStrList.indexOf(group, 0), 3, new QStandardItem(""));
 
 
    }

TreeView

Next comes the assignment of a contact to appropiate parent node i.e group item.

int row1 = 0;
   // QStandardItem* imageData;
    //imageData = new QStandardItem();
 
    for(QList<BuddyInfoList>::iterator i = buddy_list.begin(); i!=buddy_list.end(); ++i)
    {
        QString group = (*i).group();
 
        for(QList<QStandardItem*>::iterator j = groupList.begin(); j != groupList.end(); ++j)
        {
            if((*j)->accessibleText()== group)
            {
                if((*j)->hasChildren())
                {
                    row1 = (*j)->rowCount();
                }
                else
                {
                    row1 = 0;
                }
                (*j)->setChild(row1, 1, new QStandardItem((*i).DisplayName()));
                (*j)->setChild(row1, 2, new QStandardItem((*i).phone()));
                //(*j)->setChild(row1, 2, new QStandardItem((*i).group()));
                (*j)->setChild(row1, 3, new QStandardItem(CommonUtilities::QintToQString((*i).dbBuddyId())));
 
                QByteArray temp = (*i).buddyPhoto();
                QPixmap* pixmap;
                pixmap = new QPixmap();
                pixmap->loadFromData(temp);
                *pixmap = pixmap->scaledToHeight(25);
                *pixmap = pixmap->scaledToWidth(25);
                QStandardItem* imageData;
                imageData = new QStandardItem();
 
 
 
                //imageData->setData(QVariant(QPixmap::fromImage(image)), Qt::DecorationRole);
                imageData->setData(QPixmap(*pixmap), Qt::DecorationRole);
                (*j)->setChild(row1, 0, imageData);
 
 
 
            }
        }
 
        //row1++;
 
    }

Leave a Reply

Your email address will not be published. Required fields are marked *