【问题标题】:Read File Using Relative Path on Linux Qt在 Linux Qt 上使用相对路径读取文件
【发布时间】:2014-09-26 02:45:15
【问题描述】:

原件:QFile file("/home/casper/QuickRecorder/about_content.txt");(工作)

我试过了:

  1. "about_content.txt"
  2. "/about_content.txt"
  3. "~/about_content.txt"
  4. "./about_content.txt"
  5. "QuickRecorder/about_content.txt"
  6. "/QuickRecorder/about_content.txt"
  7. "~/QuickRecorder/about_content.txt"
  8. "~/QuickRecorder/about_content.txt"

没有人工作。=[


我的问题

  1. 我可以使用什么路径?
  2. 如果我将文件“about_content.txt”注册到Resource,如何将其读入文本浏览器?

以下是完整代码:

About::About(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::About)
{
    ui->setupUi(this);
    this->setFixedSize(this->width(),this->height());
    QFile file("/home/casper/QuickRecorder/about_content.txt");
    if ( !file.open(QIODevice::ReadOnly) )
        QMessageBox::information(0, "Error", file.errorString());
    QTextStream content(&file);
    ui->aboutContentBrowser->setText(content.readAll());
}

参考:QT C++ GUI Tutorial 27- How to read text file and display file to a textbrowser or textEdit


感谢您的帮助。

【问题讨论】:

    标签: qt path resources relative-path qfile


    【解决方案1】:

    如果您将文件 about_content.txt 放在构建目录中,您可以使用:

    • about_content.txt
    • ./about_content.txt

    如果您必须直接从此路径打开文件/home/casper/QuickRecorder/about_content.txt

    • 使用您所写的绝对路径。

    如果你想使用相对路径

    看看relative path vs absolute path 的区别。因此,例如,如果您将文件放置到 /home/casper/QuickRecorder/about_content.txt 并且您确切地知道您的构建目录是 /home/casper/app-build - 您可以使用相对路径 ../QuickRecorder/about_content.txt

    看看QDir 类。它已经包含许多有用的方法。

    如果您想将文件放置到资源中

    这个过程非常简单。只需将资源添加到您的项目并根据The Qt Resource System 将文件添加到您的资源。例如,您可以将您的文件about_content.txt 添加到.qrc 文件中,并以这种方式在您的程序中使用它:QFile file(":/about_content.txt");

    【讨论】:

      【解决方案2】:

      可以使用静态函数QDir::homePath()获取用户主目录的路径。

      QString homePath = QDir::homePath();
      QFile file(homePath + "/QuickRecorder/about_content.txt");
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-16
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        • 2014-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多