QStandardItem TreeView


Create a new Qt application. Drag a treeview onto the designer surface. Apply horizontal layout tthe treeview. Add the init() method and declare the QStandardItemModel model in dialog.h



class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = nullptr);
    ~Dialog();

private:
    Ui::Dialog *ui;

    QStandardItemModel model;
    void init();

};



In dialog.cpp, call init() from the constructor:



Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    init();
}

Inside init, setup the treeview and display it:



void Dialog::init()
{
    QStringList headers;
    headers << "My Items";
    model.setHorizontalHeaderLabels(headers); //set the header labels.

    QStandardItem *root = model.invisibleRootItem(); //invisible root item is the root of all the items.
    for(int p = 0; p < 100; p++)
    {
        QStandardItem * parentItem = new QStandardItem(QString("Parent %0").arg(p)); //first level of the tree
        root->appendRow(parentItem);
        for(int c = 0; c < 5; c++)
        {
            QStandardItem *childItem = new QStandardItem(QString("Child %0").arg(c));  //second level of the tree
            parentItem->appendRow(childItem);
            for(int s = 0; s < 2; s++)
            {
                QStandardItem *subChild = new QStandardItem(QString("Subchild %0").arg(s)); //third level of the tree
                childItem->appendRow(subChild);
            }
        }
    }
    ui->treeView->setModel(&model);
}
The result looks like the following:


Comments

Popular posts from this blog

QTreeView and QTableView dynamic changes

C++ Tour Part III

C++ strings and string_view