我将非常感谢您的帮助!
我创建了一个自定义对象,继承自QQuickPaintedItem并将其发送到QML应用程序。
进展顺利,但存在一些问题。
每次小部件更改其自身大小时,我都需要重新绘制缩放的图像。但我无法理解如何在C++中制作它。它只调用一次 paint 方法。
有什么建议吗?
源代码:我的形象
#ifndef MYIMAGE_H
#define MYIMAGE_H
#include <QQuickPaintedItem>
#include <QQuickItem>
#include <QPainter>
class MyImage : public QQuickPaintedItem
{
Q_OBJECT
public:
explicit MyImage(QQuickItem *parent = 0);
void paint(QPainter* painter) override;
signals:
public slots:
};
#endif // MYIMAGE_H
我的形象.cpp
#include "layerimage.h"
MyImage::MyImage(QQuickItem *parent) : QQuickPaintedItem(parent)
{
setImplicitWidth(600);
setImplicitHeight(600);
}
void MyImage::paint(QPainter *painter)
{
QImage firstImage("e:/image1.png");
QImage secondImage("e:/image2.png");
secondImage = secondImage.mirrored(false, true);
firstImage = firstImage.scaled(width(), height(),Qt::KeepAspectRatio);
secondImage = secondImage.scaled(width(), height(),Qt::KeepAspectRatio);
painter->drawImage(0,0, firstImage);
painter->setOpacity(0.5);
painter->drawImage(0,0, secondImage);
}
主.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "myimage.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<MyImage>("CustomImage", 1, 0 , "MyImage");
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
主.qml
import QtQuick 2.5
import QtQuick.Controls 1.3
import CustomImage 1.0
ApplicationWindow {
visible: true
width: 900
height: 900
minimumWidth: 900
minimumHeight: 480
title: qsTr("Checker")
Rectangle
{
id: image
color: "transparent"
border.color: "red"
anchors
{
margins: 20
centerIn: parent
fill: parent
}
MyImage
{
anchors
{
centerIn: parent
}
}
}
}
Okey。我找到了解决方案。似乎我需要使我的图像元素锚点.fill:父。或者将宽度和高度设置为等于父大小。之后,它将在每个调整大小的窗口时刻调用油漆!