我无法在QML中加载具有绝对文件路径的图像。 每次我收到以下错误:
QML Image: Cannot open: "file//d/folder/image1.jpg"
在Ubuntu下,它完美无缺。
此代码将动态设置图像:
Image {
id: img
x: 0
y: 25
width: 227
height: 230
anchors.horizontalCenter: parent.horizontalCenter
source: "file://"+path
fillMode: Image.PreserveAspectFit
}
我及时测试了以下命令,如果我点击了图片:
onClicked:{
console.log(path)
}
比得到当前的路径:D:/folder/image1.jpg
是否有针对Windows的解决方法?
问候
答案 0 :(得分:13)
“file // d / folder / image1.jpg”不是有效的网址。它应该是“file:/// d:/folder/image1.jpg”。
答案 1 :(得分:3)
好的,我找到了解决方案。
我实现了一个QDeclarativeImageProvider
来处理c ++中的图像路径并返回一个PixelMap。
如果您有兴趣:
#ifndef IMAGEPROVIDER_H
#define IMAGEPROVIDER_H
#include <QDeclarativeImageProvider>
class ImageProvider : public QObject, public QDeclarativeImageProvider
{
Q_OBJECT
public:
ImageProvider(QDeclarativeImageProvider::ImageType type);
~ImageProvider();
QImage requestImage(const QString& id, QSize* size, const QSize& requestedSize);
QPixmap requestPixmap(const QString& id, QSize* size, const QSize& requestedSize);
};
#endif // IMAGEPROVIDER_H
#include "imageprovider.h"
#include <QFile>
#include <QImage>
#include <QPixmap>
#include <QDebug>
ImageProvider::ImageProvider(QDeclarativeImageProvider::ImageType type) :
QDeclarativeImageProvider(type){}
ImageProvider::~ImageProvider(){}
QImage ImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize)
{
QImage image(id);
QImage result;
if (requestedSize.isValid()) {
result = image.scaled(requestedSize, Qt::KeepAspectRatio);
} else {
result = image;
}
*size = result.size();
return result;
}
QPixmap ImageProvider::requestPixmap(const QString& id, QSize* size, const QSize& requestedSize)
{
QPixmap image(id);
QPixmap result;
if (requestedSize.isValid()) {
result = image.scaled(requestedSize, Qt::KeepAspectRatio);
} else {
result = image;
}
*size = result.size();
return result;
}
view->engine()->addImageProvider(QString("extern"), imageProvider);
Image {
id: img
x: 0
y: 25
width: 227
height: 230
anchors.horizontalCenter: parent.horizontalCenter
source: "image://extern/"+path
//doesn't find absolute path in windows source: "file://"+path
fillMode: Image.PreserveAspectFit
}
答案 2 :(得分:0)
请使用以下路径"qrc:///your_imagepath"