QTreeView selection


Create a new Qt Widgets application. Drag a treeview and line edit onto the designer surface and place them in vertical layout, as follows:




Add selection model, standard item model, and slot for selection changed to the header as follows:


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QStandardItemModel>
#include <QItemSelectionModel>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private:
    Ui::MainWindow *ui;
    QStandardItemModel model;
    QItemSelectionModel *selectionModel;
    void init();

private slots:
    void onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
};
#endif // MAINWINDOW_H

Populate the treeview as follows (see init() function in mainwindow.cpp). Contents of mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardItem>
#include <QObject>
#include <QDebug>

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

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{
   QStringList headers;
   headers << "My Items";
   model.setHorizontalHeaderLabels(headers);

   QStandardItem *root = model.invisibleRootItem();
   for(int p = 0; p < 5; p++)
   {
       QStandardItem *parentItem = new QStandardItem(QString("Parent %0").arg(p));
       root->appendRow(parentItem);
       for(int c = 0; c < 5; c++)
       {
           QStandardItem *childItem = new QStandardItem(QString("Child %0").arg(c));
           parentItem->appendRow(childItem);
           for(int s = 0; s < 5; s++)
           {
               QStandardItem *subchild = new QStandardItem(QString("SubChild %0").arg(s));
               childItem->appendRow(subchild);
           }
       }
   }
   ui->treeView->setModel(&model);
   selectionModel = new QItemSelectionModel(&model);
   ui->treeView->setSelectionModel(selectionModel);
   connect(selectionModel,&QItemSelectionModel::selectionChanged,this,&MainWindow::onSelectionChanged);
}

void MainWindow::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
    auto list = selected.indexes();
    auto firstIndex = list.first();
    auto selectedData = ui->treeView->model()->data(firstIndex).toString();
    ui->lineEdit->setText(selectedData);
}

Inside the init() function, set the item selection model as shown (first initialize it from the QstandardItemModel and then set treeview's selection model to the newly initialized selection model).

 Implement the onSelectionChanged function as shown, by grabbing the first index of the selected indices, and getting the model data from that index.

Comments

Popular posts from this blog

QTreeView and QTableView dynamic changes

C++ strings and string_view

C++ Tour Part III