1

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

如何使在 mainwindow/treeview 中查看的文件运行?

要查看的文档是具有静态路径的纯文本文档。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
4

1 回答 1

2

如果要使用默认文本查看器打开文件:

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();
    }
}
于 2013-12-12T07:34:23.950 回答