#ifndef CUSTIMAGE_H
#define CUSTIMAGE_H
#include <QObject>
#include <QQuickPaintedItem>
#include <QPainter>
#include <QImage>
//继承自基于QML可绘制项
class CustImage : public QQuickPaintedItem
{
Q_OBJECT
public:
//构造
CustImage(QQuickItem *parent = 0);
//析构
~CustImage();
//单例
static CustImage *getInst();
//更新图像
void UpdateImage(QImage _image);
//QML调用函数
//初始化
Q_INVOKABLE void init();
//清空图像
Q_INVOKABLE void clear();
public:
//接口重写
void paint(QPainter *painter);
signals:
private slots:
private:
QImage m_baseImage{nullptr};//图像对象
int m_Width{1920};
int m_Height{1080};
};
#endif // CUSTIMAGE_H
#include "custimage.h"
//全局对象
static CustImage *_inst;
//构造
CustImage::CustImage(QQuickItem *parent) : QQuickPaintedItem(parent)
{
_inst = this;
init();
}
//析构
CustImage::~CustImage()
{
}
//单例
CustImage *CustImage::getInst()
{
if(nullptr==_inst){
_inst = new CustImage;
}
return _inst;
}
//更新图像
void CustImage::UpdateImage(QImage _image)
{
this->m_baseImage = _image;
update();
}
//初始化
void CustImage::init()
{
m_baseImage = QImage(m_Width,m_Height,QImage::Format_ARGB32);
if(this->m_baseImage.load(":/test.jpg")){
update();
}else{
m_baseImage.fill(Qt::black);
}
}
//清空图像
void CustImage::clear()
{
this->init();
}
//绘制图像
void CustImage::paint(QPainter *painter)
{
painter->drawImage(
QRectF(0,0,m_baseImage.width()*0.5,m_baseImage.width()*0.5),//绘制区域
m_baseImage.copy()); //图像
}
import QtQuick 2.15
import QtQuick.Window 2.15
import CppImage.CustImage 1.0
Window {
width: 640
height: 480
visible: true
title: qsTr("CustImage Draw From CPP")
Rectangle{
anchors.fill: parent
color:"red"
Rectangle{
anchors.centerIn: parent
color: "blue"
width: parent.width*0.9
height: parent.height*0.9
CustImage{
id:custImg
anchors.centerIn: parent
width: parent.width*0.9
height: parent.height*0.9
}
}
}
}