从treeView和QFileSystemModel运行Qt5文件

Qt 5 running file from treeView and QFileSystemModel

本文关键字:Qt5 文件 运行 QFileSystemModel treeView      更新时间:2023-10-16

问题是我最近才开始c++编程。我的问题如下:

如何使在主窗口/树视图中查看的文件运行?

要查看的文档是具有静态路径的纯文本文档。sPath是文件所在目录的路径。

下面是我的"mainwindow.cpp"文件。

#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)
{
};

下面是我的"mainwindow.h"文件。

#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

如果您想用默认文本查看器打开文件:

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

或者,如果你想通过你的Qt应用程序打开文本文件,它应该是:

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();
    }
}