Muhammad Bilal Maqsood Muhammad Bilal Maqsood - 1 year ago 86
C++ Question

QPixmap not working with image path stored in variable

when I write the image path directly like this

QPixmap imgBtry("/some/path/resources/Battery100.png");

it works perfectly but its not working when i store the path in a variable. What should i do? Following is the complete code.

//global variables
std::string path;
std::string img100 = "/some/path/resources/Battery100.png";
std::string img75 = "/some/path/resources/Battery75.png";
std::string img50 = "/some/path/resources/Battery50.png";
std::string img25 = "/some/path/resources/Battery25.png";

MainWindow::MainWindow(QWidget *parent) :
ui(new Ui::MainWindow)
QPixmap imgBtry(img50);

Answer Source

What error do you get? A guess could be:

The QPixmap constructor takes a QString as argument. It works when you put the string directly because it is a c-string (char *) and QString have an constructor taking an c-string as input. But have no constructor taking a std::string as input.

So either:

1) define your strings as c-strings.


2) convert your std::strings to c-strings before calling QPixmap:

QPixmap imgBtry(img50.c_str());