2

I tryed a lot of things but they didnt work.

I'm using Qt 5.9.1 and i wouldlike to open a .txt file (which is in a qrc file) in a QFile variable, like this :

QFile file(":/txt/config");

I also tried to use

QFile file("qrc:/txt/config"); 

Here's the qrc file (summarized) :

<qresource prefix="/txt">
    <file alias="config">resources/files/config.txt</file>
</qresource>

My .pro does have INCLUDEPATH += .

I have already tryed to :

Build -> Clean all
Build -> Run qmake
Build -> Build all

And it changed nothing, at every launch, I have this output :

QIODevice::read (QFile, ":/txt/config"): device not open

The path in .qrc is correct, QtCreator find the file when i browse the directories and open it in editor like a normal text file

Thanks for your help, and sorry for my english ... (and the edit function does not allow me to add hello everyone on the top, so i say it here :) )

NicoTine
  • 51
  • 3
  • 12
  • If the filename is config.txt, why are you trying to open txt/config? Those are clearly different filenames. – MrEricSir Sep 23 '17 at 16:38
  • Because i use alias "config". I also tried to open config.txt and /txt/resources/files/config.txt. Didn't work – NicoTine Sep 23 '17 at 16:43
  • I just tested it, the code seems fine. Probably a problem with qmake not regenerating files. Sometimes `make clean` and/or `qmake` does not help. Try deleting `Makefile` and/or generated `qrc_yourAppName.cpp`. – LeBlue Sep 23 '17 at 16:49
  • Do you have `RESOURCES += appName.qrc` or someting similar in the qmake/project file? – LeBlue Sep 23 '17 at 16:51
  • have you used `file.open(QFile::ReadOnly)`? – eyllanesc Sep 23 '17 at 17:02
  • I used `file.open(QIODevice::ReadWrite | QIODevice::Text)`. I tried with `file.open(QIODevice::ReadOnly | QIODevice::Text)` and it worked ... – NicoTine Sep 23 '17 at 17:08
  • I have also removed the whole folder generated by Qt before editing QIODevice. `QFile::ReadOnly` works too ! Thanks everybody – NicoTine Sep 23 '17 at 17:14
  • But `QFile::WriteOnly` doesn't work :( I have checked the config's file permission. They are on "Read and write" for everything – NicoTine Sep 23 '17 at 17:27
  • 1
    Writing will not work, as the file/resources contents are put into the binary/executable (via the qrc_appname.cpp file). You can't edit that. If you want to edit that, you need a plain file, not a resource – LeBlue Sep 23 '17 at 18:17
  • If you want to add a writeable config file to your application, have a look at [QSettings](http://doc.qt.io/qt-5/qsettings.html) – LeBlue Sep 23 '17 at 18:21
  • Oh thank you, I didnt know it exists ! It will make me the life easier ! – NicoTine Sep 23 '17 at 19:19

1 Answers1

6

You cannot open a resource file for writing, as the content is embedded in the application binary. You have to open it readonly:

QFile file(":/txt/config");
if(!file.open(QIODevice::ReadOnly)) {
    qDebug() << "error: " << file.errorString();
}
LeBlue
  • 595
  • 7
  • 11