QPixmap 不适用于存储在变量中的图像路径

QPixmap not working with image path stored in variable

当我直接这样写图片路径时

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

它工作得很好,但是当我将路径存储在变量中时它不起作用。我应该怎么办?以下是完整代码。

//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) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QPixmap imgBtry(img50);
    ui->label_2->setPixmap(imgBtry.scaled(50,50,Qt::IgnoreAspectRatio,Qt::FastTransformation));
}

你得到了什么错误?猜测可能是:

QPixmap 构造函数将 QString 作为参数。当您直接放置字符串时它会起作用,因为它是一个 c 字符串 (char *) 并且 QString 有一个将 c 字符串作为输入的构造函数。但是没有构造函数将 std::string 作为输入。

所以要么:

1) 将您的字符串定义为 C 字符串。

2) 在调用 QPixmap 之前将您的 std::string 转换为 C 字符串:

QPixmap imgBtry(img50.c_str());