Microsoft Visual Studio: Loading resources in Qt application (without plug-in) - c++

We don't have a Qt plug-in installed for MSVS, and it makes me wonder how/whether it is possible to load resources (images, etc) to the application.

Yes, you can load ressources.
Unfortunately, the qrc Editor which create qrc files is part of the Qt Addin for VS...
But you can create this xml file by hands, for the format see here
Once the qrc file created, you have at least two possibilities :
A) Use qmake
Add a reference to your qrc file in your pro file :
RESOURCES = ApplicationResources.qrc
Regenerate your vcproj from your pro by using qmake
qmake -tp vc
B) If you don't generate your vcproj file from your pro file, you can :
Add manually your qrc file in your solution, for example in the following path :
Resource Files/Res/ApplicationResources.qrc
Add the following commands in the properties of the qrc file in visual studio :
command line : $(QTDIR)\bin\rcc.exe -name ApplicationResources res\ ApplicationResources.qrc -o $(IntDir)\qrc__ ApplicationResources.cpp
Description : RCC res/ApplicationResources.qrc
Output : $(IntDir)\qrc__ ApplicationResources.cpp
C) You can also use an external binary resources file
The command line :rcc -binary myresource.qrc -o myresource.rcc
In the application, you have to register the resource file :
QResource::registerResource("/path/to/myresource.rcc");
For using resource file in the source code see the doc
However, like cheez, I also suggest using qmake and pro file and do not edit properties by hand in Visual Studio...
Hope this helps !

Use the qrc executable to generate a cpp file which you can include in your project:
/usr/local/Trolltech/Qt-4.5.1/bin/rcc -name core core/core.qrc -o build/release/core/qrc_core.cc
See http://doc.trolltech.com/4.0/resources.html
However, I strongly suggest using qmake or some other build system to automate this for you.

Related

Using preload-file compiler option for emscripten compiler to load local file in Qt

I am building an Qt Application using WebAssembly. I want to open a local file and read it frin my code which isn't exacty easy with WebAssembly. I tried using the preload-file option (reference) in my .pro file:
CONFIG += preload-file /path/to/file/Settings.ini
However, when compiling my application with WebAssembly, It fails showing my the following error:
Application exit (RuntimeError: Aborted(native code called abort()))
I am currently using Qt 6 with the fitting Emscripten version. My code works when compiling with GCC. Of course, emscripten compiles when removing the file handling stuff from my code. Using a file dialog isn't a suitable option.
I noticed you are using CONFIG += but the emscripten reference says it is a linker flag. Try using instead QMAKE_LFLAGS += --preload-file /path/to/file/Settings.ini.
Personally, I have not tested preload-file option but two other options have been working for me:
The similar embed-file functionality. In the .pro file add QMAKE_LFLAGS += --embed-file ../../cdpcore/Templates/Models#Models to make the folder specified to be available in [working directory]/Models.
Use the Qt Resource system to embed files. Basically add a .qrc file to your project that lists resources to embed into the binary and then into the .pro file add RESOURCES += resources.qrc.

Embedding manifest to exe file

I have a .manifest file which is linked with a .exe program file so that it asks for admin privileges when opened. Now it is a separate file called program_name.exe.manifest which is is the same folder as program_name.exe. Is there any way by which we can embed the manifest file into the .exe file so that it can be one single file instead of two.
BTW the program is created using C++
Yes. Declare the manifest as a resource and then just build the resource object file and link it to your exe.
In your resource.rc file, define your manifest resource like so:
IDR_RT_MANIFEST1 RT_MANIFEST "program_name.exe.manifest"
In your resource.h file declare it with the value 1
#define IDR_RT_MANIFEST1 1
Build the resource file with windres: windres resource.rc -o resource.o
Link the resource when building your project: -l resource.o
.........................................................................
If your're using Visual Studio you don't need to build it explicitly, but there are 2 options which should be set beforehand:
1) Project > Project_Name Properties > Configuration Properties > Linker > Manifest File -> Generate Manifest set to No
2) Project > Project_Name Properties > Configuration Properties > Manifest Tool > Embed Manifest set to Yes
Also add your manifest file to your project as existing item.
If you are using windows CL, like powershell, try
program_name.exe –manifest program_name.exe.manifest -outputresource:program_name.exe;1
That should do the trick.

Force rcc-ing of qrc file on each build

How to force rcc-ing of a qrc file on each build in Visual Studio 2015? We are embedding the resources in the binary, so if something like qml or image assets change, we need to run rcc to get a fresh .cpp file for the current state. I see several options - brutally touching the .qrc file in a pre build event, running a script which checks everything in the asset folder before build and checking the timestamps and comparing them to a state at the previous build. Are there cleaner and more elegant options?
If you were to use CMake, you could add a pre-build task to delete the your-project-name_autogen folder from the build directory. This forces CMake to rcc the qrc file each build.
The command might look something like:
add_custom_command (TARGET your-project-name PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_BINARY_DIR}/your-project-name_autogen)
CMake does this by adding a Pre-Build Event to its generated Visual Studio project, so you can also replicate it with only Visual Studio. If you haven't found the pre-build event section already, right-click on the desired project (not solution), and select Properties. Under Build Events, there should be a section called Pre-Build Events. A command like del your-files would probably suffice.
The answer linked below gave some other decent options.
How to delete files in Visual Studio Pre-build event command line
The CMake command was the solution to my issues with a Qt qrc file containing QML resources.
Since it was requested in the comments, I'm publishing the solution I came up with. So, in my case the qrc file is added to the Visual Studio solution, and has a proper Custom Build Tool set (but that is the common way and should be set up by the VS Qt plugin) like this:
All I had to do was to make a trivial C# program which reads the contents of the qrc and updates the modification timestamp of the qrc file, if any of the contained items was newer than the qrc itself. This is all it takes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;
namespace QrcValidator
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
System.Console.WriteLine("usage: QrcValidator.exe <qrc file path>");
return;
}
Console.WriteLine(string.Format("Validating {0}", args[0]));
XDocument qrcDocument = XDocument.Load(args[0]);
var qrcFileLastWrtieTimeUtc = File.GetLastWriteTimeUtc(args[0]);
foreach (var file in qrcDocument.Descendants("RCC").Descendants("qresource").Descendants("file"))
{
if (File.GetLastWriteTimeUtc(file.Value) >= qrcFileLastWrtieTimeUtc)
{
Console.WriteLine("{0} is dirty, setting last write time of {1} to current UTC time", file.Value, args[0]);
File.SetLastWriteTimeUtc(args[0], DateTime.UtcNow);
Environment.Exit(0);
}
}
}
}
}
This tool takes the qrc file as the first argument. So I just added calling this tool as a pre build event, and if any changes have happened to the resources, the qrc file is touched, and it's normal build command is invoked.

Using External Binary Resource

I'm on a project that used to have Compiled-in Resources.
Now, the user can choose the theme that he wants to work on. No problems until there, in a little research I started to use the External Binary Resource approach.
My resources were build successfully and the QResource::registerResource("/path/to/myresource.rcc"); returns true.
It is not working properly though. Apparently the compiled-in resource is still there, in the executable. I can't see the different icons stored in my external binary resource.
How do I remove this compiled-in resource? Do I need to do that to work properly?
Assuming you are using a .pro file for your project, you need to remove the resource file from the RESOURCES list. If you still want it to be listed in your project, you can use OTHER_FILES.
Before:
RESOURCES += file1.qrc file2.qrc
After:
RESOURCES += file2.qrc
OTHER_FILES += file1.qrc
If you want to go a step further you can automate the build of qrc files:
RCC_BINARY_SOURCES += file1.qrc
asset_builder.commands = $$[QT_HOST_BINS]/rcc -binary ${QMAKE_FILE_IN} -o ${QMAKE_FILE_OUT} -no-compress
asset_builder.depend_command = $$[QT_HOST_BINS]/rcc -list $$QMAKE_RESOURCE_FLAGS ${QMAKE_FILE_IN}
asset_builder.input = RCC_BINARY_SOURCES
asset_builder.output = $$OUT_PWD/$$DESTDIR/${QMAKE_FILE_IN_BASE}.qrb
asset_builder.CONFIG += no_link target_predeps
QMAKE_EXTRA_COMPILERS += asset_builder
OTHER_FILES += $$RCC_BINARY_SOURCES
You have to change the way the resources are compiled. By default, every resource file (resources.qrc, for example) included in a Qt project is compiled to C++ code (the qrc_resources.cpp you've probably seen after compiling the project). That makes the resource is compiled and linked with your executable (or library). The Qt for Visual Studio plugin does exactly that: adds a custom build step to every QRC file. Open the properties of the QRC file to take a look (right-click on the QRC file, then Properties):
Command line: "$(QTDIR)\bin\rcc.exe" -name "%(Filename)" -no-compress "%(FullPath)" -o .\GeneratedFiles\qrc_%(Filename).cpp
Outputs: .\GeneratedFiles\qrc_%(Filename).cpp
%(Filename) is, as you can figure out, the extension-less name of the file
To avoid this behaviour just remove the QRC file from the project. Of course, the problem is that you'll have to manually build the .rcc file. You can do it using a script as part of your makefile.
On the other hand, if you're using Visual Studio, you can change the command used to compile it, adding the -binary option to the rcc tool so it compiles to an external file. In this way it will be included in your usual compilation workflow:
Command line: "$(QTDIR)\bin\rcc.exe" -name "%(Filename)" "%(FullPath)" -binary -o "%(Outputs)"
Outputs: $(OutDir)\%(Filename).rcc - it is different from screenshot because I took it from an existing project, use the one in the text to place the RCC file in the same dir of your executable.
Important note: be sure you change the build tool for all the configurations.
If you use a makefile or Qt Creator instead, you can use this as a base to create the needed script.
Hope this can help you.

Qt: Path to file in QString

I have problem with storing a path to file in Windows in a QString. I'm using Qt with C++.
QString resourcePath = ":/images/frog.bmp";
if( ! QFile::exists(resourcePath) )
{
qDebug("*** Error - Resource path not found : %s", resourcePath.data());
}
This code results with this:
*** Error - Resource path not found : :
So I can see that resourcePath.data()) contains just ":". I assumed that the problem is with slashes, so I tried changing "/" with "\" but the result is the same.
But if I write:
QString resourcePath = "C:\\Users\\Boris\\Desktop\\Frogger3\\images\\frog.bmp";
everything works just fine. What am I missing? Is there a reason why colon cant be the first sign in QString? How should I write path to the file in the same folder as the code?
Thanks in advance!
The style of resource path you are using is implying that the file frog.bmp is in a resource file. So either you need to resolve the path of the bmp file at run-time, or you need to add a resource file to your project.
If you use the UI designer the concept of resource files is handled automatically, but if you want to access resources through code there are a few things you need to do.
First create a resource file. In visual studios (with the visual studios add-in) there is a wizard to do this. Essentially it is just an xml file with the extension .qrc looking something like this:
<RCC>
<qresource prefix="/images">
<file>frogger.bmp</file>
</qresource>
</RCC>
Now this file has to be processed during the build. If you have used .ui files, it is similar. There is a tool called "rcc.exe" that takes the qrc file as an input and generates a .cpp file that needs to be compiled and linked with your project.
If you are using visual studios and have the Qt Visual Studios Plugin, this should all be handled for you when you add the qrc file to the project.
If you are using QMake then your pri file should contain a "RESOURCES" section where you need to list your qrc file something like:
RESOURCES += yourqrcfile.qrc
Now, once that is done. You can access your resources in code. Your call to QFile::exists should resolve the file name.
In the case where you put your resources in a static or shared library, you will need to add the following line to your class to ensure that the resource file is loaded.
Q_INIT_RESOURCE(yourqrcfile); // do not include the extension, just the name of the file.
Here are a few links that explain things in more detail:
Creating a resource file in Qt Creator
Explaining how resource files work