QPixmap不能使用存储在变量中的图像路径

QPixmap not working with image path stored in variable

本文关键字:图像 路径 变量 不能 存储 QPixmap      更新时间:2023-10-16

当我像这样直接写入图像路径

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-string (char *),并且QString有一个构造函数将c-string作为输入。但是没有以std::string作为输入的构造函数。

:

1)将字符串定义为c-string。

2)在调用QPixmap:

之前将std::string转换为c-string
QPixmap imgBtry(img50.c_str());