QML
import QtQuick 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.2
Column
{
width:640
height:400
Image
{
id:image
width:640
cache: false
source: "image://colors/red"
}
Connections
{
target: imagecontext
onCallQmlRefeshImg:
{
image.source = ""
image.source = "image://imageprovider"
console.log("refresh.");
}
}
}
ImageProvider
class ColorImageProvider : public QQuickImageProvider
{
public:
ColorImageProvider()
: QQuickImageProvider(QQuickImageProvider::Pixmap)
{
}
QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override
{
int width = 100;
int height = 50;
if (size)
*size = QSize(width, height);
QPixmap pixmap(requestedSize.width() > 0 ? requestedSize.width() : width,
requestedSize.height() > 0 ? requestedSize.height() : height);
pixmap.fill(QColor(id).rgba());
return pixmap;
}
};
class ImageProvider : public QQuickImageProvider
{
public:
ImageProvider::ImageProvider(ImageType type, Flags flags = Flags()) :
QQuickImageProvider(type, flags)
{
}
~ImageProvider(){}
QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
return image;
}
QImage image;
};
ImageContext
class ImageContext : public QObject
{
Q_OBJECT
public:
ImageContext(QObject* parent = 0);
ImageProvider* m_imageProvider = nullptr;
public slots:
void setImage(const QImage& image);
signals:
void callQmlRefeshImg();
};
ImageContext::ImageContext(QObject* parent):
QObject(parent)
{
m_imageProvider = new ImageProvider(QQuickImageProvider::Image);
}
void ImageContext::setImage(const QImage& image)
{
m_imageProvider->image = image;
emit callQmlRefeshImg();
}
注册和相应
qml->engine()->addImageProvider(QLatin1String("colors"),new ColorImageProvider);
ImageContext* context = new ImageContext(this);
qml->engine()->rootContext()->setContextProperty("imagecontext",context);
qml->engine()->addImageProvider(QLatin1String("imageprovider"),context->m_imageProvider);
qml->setSource(QUrl("image.qml"));
QDir dir("E:/MyVideoPlayer/Win32/Release/capture");
QStringList files = dir.entryList(QDir::Files,QDir::SortFlag::Time | QDir::SortFlag::Reversed);
qDebug() << "files:" << files.size();
connect(button, &QPushButton::clicked,[=]()
{
static int current = 0;
auto list = qml->rootObject()->childItems();
if(current == files.size())
current = 0;
QImage image;
QString file = QString("E:/MyVideoPlayer/Win32/Release/capture/") + files.at(current);
qDebug() << "loaded:" << image.load(file) << "," << file<<","<<current;
context->setImage(image);
current++;
}
);