user2998144
user2998144

Reputation: 21

Qt 5 running file from treeView and QFileSystemModel

The issue is that I've only recently started c++ programming. My question is as follows:

How do I make the file viewed in mainwindow/treeview run?

The document to view is a plain text document with a static path. sPath is the path to the directory where the files reside.

What follows here is my "mainwindow.cpp" file.

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDirModel"
#include "QTreeView"
#include "QFileSystemModel"
#include "QtGui"
#include "QtCore"
#include "QDir"

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

    QString sPath ="/home/simon/QT Projects/Bra_Programmering/utlatanden/";

    filemodel = new QFileSystemModel(this);
    filemodel->setFilter(QDir::Files | QDir::NoDotAndDotDot);
    filemodel->setNameFilterDisables(false);
    filemodel->setRootPath(sPath);
    ui->treeView->setModel(filemodel);
    ui->treeView->setRootIndex(filemodel->setRootPath(sPath));
}

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

void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{

};

What follows here is my "mainwindow.h" file.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <mainwindow.h>
#include <QtCore>
#include <QtGui>
#include <QDirModel>
#include <QFileSystemModel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:

    void on_treeView_doubleClicked(const QModelIndex &index);

private:
    Ui::MainWindow *ui;
    QFileSystemModel *filemodel;
};

#endif // MAINWINDOW_H

Upvotes: 1

Views: 2369

Answers (1)

Antonio Dias
Antonio Dias

Reputation: 2881

If you want to open the file with the default text viewer:

void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{
    QDesktopServices::openUrl(QUrl::fromLocalFile(filemodel->filePath(index)));
}

Or if you want to open the text file by your Qt application it should be:

void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{
    QFile file(filemodel->filePath(index));

    if(file.open(QFile::ReadOnly | QFile::Text))
    {
        QTextStream in(&file);
        QString text = in.readAll();
        // Do something with the text
        file.close();
    }
}

Upvotes: 2

Related Questions