PDA

View Full Version : QModelIndexList: getting 4 QModelIndex for each item selected in a QTreeView.



robgeek
27th January 2020, 14:58
In the following code, why am I getting size 4 for QModelIndexList if I click in one file or directory only? How can I get only one path? I know I could use [0] but is there another way to get size 1?


// fsModel = QFileSystemModel
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
const QString rootPath = "/home/rob/";

fsModel = new QFileSystemModel(this);
fsModel->setRootPath(rootPath);
ui->treeView->setModel(fsModel);
ui->treeView->setRootIndex(fsModel->index(rootPath));
}

void MainWindow::on_buttonCompress_clicked()
{
QModelIndexList list = ui->treeView->selectionModel()->selectedIndexes();

qDebug() << list.size();

for (const QModelIndex &modelIndex: list)
qDebug() << fsModel->filePath(modelIndex);

// I wouldn't like to use []. I would like to get only one filepath, the one I selected.
qDebug() << fsModel->filePath(list[0]);
}

d_stranz
27th January 2020, 17:53
What are you using for your QTreeView::selectionBehavior()? SelectRows? If so, the selection model will return all QModelIndex items for each column in the row.

If you examine the QModelIndex entries in the list, I think you should see that they all have the same row() and parent() but different column() values.