qt - 在 Linux Qt 上使用相对路径读取文件

标签 qt path resources relative-path qfile

原件: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”注册到资源中,我如何将它读入文本浏览器?

完整代码如下:

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


感谢您的帮助。

最佳答案

如果您将文件 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类(class)。它已经包含了许多有用的方法。

如果你想把你的文件放到资源中

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

关于qt - 在 Linux Qt 上使用相对路径读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25104923/

相关文章:

java - 从/src/main/resources/读取文件

c# - 在 C# 中使用嵌入式资源图标作为应用程序图标

android - 获取Android文件资源的大小?

ruby-on-rails - 优胜美地的 Capybara-webkit 和 Qt5

c++ - 通过 QTimer 和 QTcpSocket 正确使用 QThread 和 moveToThread

c++ - QT中低TCP连接性能问题

wpf - 在另一个双资源中引用双资源

c++ - Qt和C++:覆盖或扩展类

git - 如何获取文件相对于 Git 存储库根目录的路径?

Java 文件输出流 : path relative to program folder?