QT5.2资源文件

QT5.2 Resource files

本文关键字:源文件 资源 QT5      更新时间:2023-10-16

简短而烦人的问题;我无法访问QT资源文件(又称.QRC)中定义的任何内容。我遵循了QT UTOARIAL创建一个名为TextFinder的窗口小部件应用程序。根据它,我创建了所有必要的文件并完成了所有指令,但我无法访问QRC内容。 在项目文件夹中,我有例如:

TextFinder
  resources
   input.txt
  main.cpp
  textfinder.cpp
  textfinder.h
  TextFinder.pro
  TextFinder.pro.user
  TextFinder.qrc
  textfinder.ui

QRC文件的内容如下:

<RCC>
    <qresource prefix="/res">
        <file>resources/input.txt</file>
    </qresource>
</RCC>

要访问我内部的文件,我在编辑器中打开了QRC,请单击该文件,然后选择复制资源路径到剪贴板选项。这产生了":/res/resources/input.txt"。因此,我刚将其输入我的功能以打开文件。此功能看起来如下:

void TextFinder::loadTextFile()
{
    QFile inputFile(":/res/resources/input.txt");
    inputFile.open(QIODevice::ReadOnly);
    if (inputFile.isOpen())
    {
        QTextStream txtStream(&inputFile);
        QString contents = txtStream.readAll();
        inputFile.close();
        ui->textEdit->setPlainText(contents);
        QTextCursor cursor = ui->textEdit->textCursor();
        cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1);
    }
    else
    {
        throw std::runtime_error("Resource file may be wrong?");
    }
}

当我运行应用程序时,runtime_error被抛出,告诉我它无法打开文件。在项目文件中,我的QRC文件定义如下:

RESOURCES += 
    TextFinder.qrc

这里出了什么问题?有人可以指出我做错了什么?

问候, 乔

根据QT资源系统文档:

也可以使用QResource标签的前缀属性指定.QRC文件中所有文件的路径前缀:

<qresource prefix="/myresources">
    <file alias="cut-img.png">images/cut.png</file>
</qresource>

在这种情况下,该文件可访问为:/myresources/cut-img.png。

因此,在存在前缀时剪切了