New blog location
New blog location
#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
#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); }
Comments
Post a Comment