How do I include a text file to a qt application?
I have text file from which I need to get data by line by line. So if my application is launched, it can read from the text file to show the information. But I don't want to supply my text file separately along with my application. How to do this? And well I have to d开发者_如何学运维o this using Qt!
I heard like using xml will be a better and easy way to accomplish this.
You have to add a qt resource file (.qrc) to your project
It might look like this:
<RCC>
<qresource prefix="/">
<file>file.xml</file>
<file>files/file2.xml</file>
</qresource>
</RCC>
After that you have to add that resource file to your project file (.pro)
Like this for example:
RESOURCES += myqrcfile.qrc
After that you can use that file in your code by using the character ':' to refer to the file
Maybe like this:
QFile data(":/file.xml");
//or
QFile data(":/files/file2.xml");
//etc...
Remember that the path that you define for the file(in the qrc) must correspond to the file's location in the filesystem as well.
Hope this helps, for more information I suggest you read the link to the documentation that Gorkem Ercan posted.
Qt Resource System is what you are looking for.
Such code works in the Qt 5.2 :
QResource common(":/phrases/Resources/Phrases/Common.xml");
QFile commonFile(common.absoluteFilePath());
if (!commonFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Unable to open file: " << commonFile.fileName() << " besause of error " << commonFile.errorString() << endl;
return;
}
QTextStream in(&commonFile);
QString content = in.readAll();
Continuing on ExplodingRat's answer.
Using QFile like that doesn't work (at least not in Qt 4.5), but you can use:
QResource r( ":/file.xml" );
QByteArray b( reinterpret_cast< const char* >( r.data() ), r.size() );
精彩评论