从 std::string 获取 QPixmap 动态图像路径

Get QPixmap dynamic image path from std::string

我对 Qt 下的 QPixmap 有疑问。我想从 std::string 动态设置 Pixmap 图像路径。我尝试了一些变化,但没有成功。

这是我的代码:

QPixmap pixmap("data/25eaad8879f1d018caec98546279804f.png"); // this is working
// label

ui->imageSite1->setPixmap(pixmap); //working

但是如果我尝试动态设置 pixmappath,我看不到图像(在标签内)。 例如

string path = "data/"+imgname+".png"; // imgname is a dynamic parameter

QPixmap pixmap(path); // this is not working

// label
ui->imageSite1->setPixmap(pixmap);

我怎样才能正确地做到这一点?

如果您查看 Documentation of QPixmap,您会看到 load 方法声明为采用 QString 作为参数。因此,您要么必须直接构建 QString(从您的示例来看,我认为这是更好的方法),要么将 std::string 转换为具有后者构造函数的 QString

我必须从文本文件加载文件路径,并且在行尾是 \n。在这种情况下,他们无法加载图像。

我删除了它并通过 load 方法加载了像素图。现在可以使用了。

string path = "data/"+imgfilepath;
QString testPath = QString::fromStdString(path);
qDebug() << testPath;
QPixmap pixmap;
pixmap.load(testPath);