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

3

原始代码: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教程27-如何读取文本文件并将其显示到textbrowser或textEdit中
2个回答

4

如果你把文件about_content.txt放在build目录里,你可以使用以下方式:

  • about_content.txt
  • ./about_content.txt

如果你必须从这个路径/home/casper/QuickRecorder/about_content.txt打开文件

  • 像你在问题中写的那样使用绝对路径。

如果你想使用相对路径

看一下相对路径和绝对路径的区别。所以,如果你将文件放置到例如/home/casper/QuickRecorder/about_content.txt,并且你确切地知道你的构建目录是/home/casper/app-build,那么你可以使用相对路径../QuickRecorder/about_content.txt

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

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

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


1
你可以使用静态函数 QDir::homePath() 获取用户主目录的路径。
QString homePath = QDir::homePath();
QFile file(homePath + "/QuickRecorder/about_content.txt");
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接