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) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    QFileSystemModel *model = new QFileSystemModel;
    ui->treeView->setModel(model);
    ui->treeView->setRootIndex(model->index("/home/"));
    connect(ui->treeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(addImgFiles()));
    }

    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));
    ui->inputImageLstBox->addItem(item);
    }

    void MainWindow::saveInputImageList(void)
    {
    outputFilename = outputDirectory + "/utsnitt24.lst";
    QFile outputFile(outputFilename);
    if(outputFile.open(QFile::WriteOnly | 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());
    outputFile.write("\n");
    }
    outputFile.close();
    }
    }@@

    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.