好的,我找到了解决方案。我QDeclarativeImageProvider
在 C++ 中实现了一个处理图像路径并返回一个 PixelMap 的方法。如果你感兴趣:
图像提供程序.h
#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
图像提供程序.cpp
#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;
}
在 mainwindow.cpp 中注册
view->engine()->addImageProvider(QString("extern"), imageProvider);
qml 文件的片段
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
}