views:

151

answers:

1

I want to display data in multiple columns in a QColumnView. I am using Qt Creator and Qt 4 for development.

Consider an address book application where you have multiple groups: Group 1, Group 2, etc. Your contacts can belong to any of those groups.

Group 1:
    John Smith
    Pocahontas
Group 2:
    Chief Powhatan
Group 3:
    ...

When a group in the first column is selected, the second column will show all contacts in that group, and when a contact is selected, their personal information is shown in a third column.

I have tried the following (based on an example from Qt Documentation):

QStringList strList1;
strList1 << "Group 1" << "Group 2" << "Group 3";

strListM1 = new QStringListModel(); // Previously declared as QStringListModel *strListM1
strListM1->setStringList(strList1);
ui->columnView->setModel(strListM1);

However, I have not been able to figure out how to add more columns, and add the contact names as children of those groups in the first column.

How can I do this? How could I add columns and rows dynamically (instead of using the QStringList like above, or any other similar method for rows)?

+2  A: 

You may rely on QStandardItem and QStandardItemModel. Here's a really simple and compilable example on how to use these classes with QColumnView:

#include <QtGui>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QMainWindow win;
    QColumnView *cview = new QColumnView;
    win.setCentralWidget(cview);

    /* Create the data model */
    QStandardItemModel model;

    for (int groupnum = 0; groupnum < 3 ; ++groupnum)
    {
        /* Create the phone groups as QStandardItems */
        QStandardItem *group = new QStandardItem(QString("Group %1").arg(groupnum));

        /* Append to each group 5 person as children */
        for (int personnum = 0; personnum < 5 ; ++personnum)
        {
            QStandardItem *child = new QStandardItem(QString("Person %1 (group %2)").arg(personnum).arg(groupnum));
            /* the appendRow function appends the child as new row */
            group->appendRow(child);
        }
        /* append group as new row to the model. model takes the ownership of the item */
        model.appendRow(group);
    }

    cview->setModel(&model);

    win.show();
    return app.exec();
}

For more details abut Qt's Model/View Programming, please refer to the official documentation.

Giuseppe Cardone