0
我將非常感謝您的幫助!Qt5和QML:小部件調整大小後如何更新QQuickPaintedItem?
我創建了一個自定義對象,繼承自QQuickPaintedItem並將其發送給QML應用程序。
它很好,但有一些問題。
每次小部件更改它自己的大小時,我都需要重新繪製縮放圖像。 但我不明白如何在C++中使用它。它只調用一次paint方法。
有什麼建議嗎?
源代碼: myimage.h
#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
myimage.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);
}
的main.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();
}
main.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。
你是什麼意思「改變自己的大小」?上次檢查時,調整項目大小時會自動調用paint()函數。 – Mitch
好吧,當我插入qDebug <<「繪畫!」進入油漆方法它只被打印一次 - 在開始。 如果我改變應用程序窗口的寬度或高度,它會像魚一樣沉默。 – ArcticNoise
請不要在每次重新繪製時從磁盤加載圖像! – peppe