Important: Please read the Qt Code of Conduct -

Application crashing after fetching filePath of the the curretnIndex of the QFileSystemModel

  • I am trying to add items from a QTreeView poplated by QFileSystemModel, I am assigning the filePath(currentIndex) to Qt:UserRole. I need this for saving the file with its ull path in a text file later on.

    @@MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)
    QFileSystemModel *model = new QFileSystemModel;

    void MainWindow::addImgFiles()
    QModelIndex index = ui->treeView->currentIndex();
    QListWidgetItem *item;
    item = new QListWidgetItem;
    item->setData(Qt::DisplayRole, model->fileName(index));
    item->setData(Qt::UserRole, model->filePath(index));

    void MainWindow::saveInputImageList(void)
    outputFilename = outputDirectory + "/utsnitt24.lst";
    QFile outputFile(outputFilename);
    if( | QFile::Text))
    for(int i = 0; i < ui->inputImageLstBox->count(); i++)
    outputFile.write(ui->inputImageLstBox->model()->index(i, 0).data(Qt::UserRole).toString().toStdString().c_str());

    When i am using the filePath I am getting a segmentation fault, and if I only use fileName then there is no error.Please help as I am really stuck.

  • You do realize that QFileSystemModel already provides this information in it's own defined roles?

  • Can u please elaborate.
    But still when I use the filePath why is the crash happening?

  • The code you show above does not compile, as model is not defined in your addImgFiles method. Otherwise, I would have said that probably model is unintialized (or 0), and thus accessing it resultsin a crash.

    Also, I don't get why you don't use the QModelIndex you get from the doubleClicked signal. That would allow you to directly access the item, without going through currentIndex. That way, you also don't need the model at all.

    Last, are you use using double-clicking is the best way to select your items. Why not use a proxy model like "this one":/wiki/QSortFilterProxyModel_subclass_to_add_a_checkbox to do your selection instead?

Log in to reply