-1

For designing a custom made pushButton I added a picture source (1):

#include "mybutton.h"
#include <QDebug>
#include <QDir>
#include <QIcon>
#include <QPixmap>

MyButton::MyButton(QWidget *parent) : QPushButton(parent) {
  QPixmap pixmap("/home/myCode/MyButton/MyButton/graphics/myPicture.png"); //(1) picture source
  QIcon buttonIcon;
  buttonIcon.addPixmap(pixmap);
  this->setIcon(buttonIcon);
  this->setIconSize(pixmap.rect().size());


}


Of course, sometimes the local path to picture changes.
So instead I would like to tell Qt at compile time something like this: Path to file is workspacefolder/graphics/myPicture.png Like in VS Code you can configure build tasks (tasks.json) for compiling with g++ and refer with variable ${workspaceFolder}.


I tried using functions of QDir-Class, but that one only return when debugging, not at compile time.

qDebug() << QDir::currentPath();

Is it possible to return the workspaceFolder with help of QDir-functions?

KeepRunning85
  • 173
  • 10
  • You probably need to pass that in from your QMake or CMake script. – drescherjm Nov 17 '20 at 18:32
  • Possible solution if you have c++20: [https://stackoverflow.com/a/57284913/487892](https://stackoverflow.com/a/57284913/487892) – drescherjm Nov 17 '20 at 18:34
  • 2
    In Qt you could also put this png file into a resource and use that in your code. [https://doc.qt.io/qt-5/resources.html](https://doc.qt.io/qt-5/resources.html) – drescherjm Nov 17 '20 at 18:36

2 Answers2

2

Qt resource system is what you need, and then the images will be "rolled into" the executable file.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
2

Like you mention adding resource file works fine.

  1. Add new file: Qt->Qt Resource File (resource.qrc)
  2. Project tree is added with "Resources"-folder
  3. Open folder
  4. Right-Click resource.qrc
  5. Add Prefix /
  6. Add image files to that prefix which are located in graphics folder
  7. Right Click on object and copy path
  8. Add copy as resource where you need it

In my above mentioned code result answer would look like this:

QPixmap pixmap(":/graphics/myPicture.png");

Qt automatically adds resource file to .pro file I guess thats the link to the compiler

RESOURCES += \
    resource.qrc

I already tested moving the project folder and renaming it. Image resources are working.

KeepRunning85
  • 173
  • 10