Save QML Image Inside C ++

I am trying to display a network image using qml and then save this image using C ++ code,

Here is the qml code,

import QtQuick 2.3
import QtQuick.Window 2.2
import com.login 1.0
Window {
    visible: true
    width : 500
    height: 500

     Login{id: login}

    MouseArea {
        anchors.fill: parent
        onClicked: {
          //  Qt.quit();
            login.save(image);
        }
    }



    Image {
        id: image
        source: "http://www.test.com/webp/gallery/4.jpg"
    }


}

And inside my boot image for login, for example,

void Login::save( QQuickItem *item)
{
    qDebug()<<"width: "<<item->width();
    qDebug()<<"height: "<<item->height();

    QQuickWindow *window = item->window();
    QImage image = window->grabWindow();

    QPixmap pix = QPixmap::fromImage(image);
    pix.save("C:/Users/haris/Desktop/output.png");
}

I get the correct width and height of the image inside the C ++ class, but the problem is that I cannot find a way to save the image element from QQuickItem.

Now I save the image, grabbing the window, which actually does not give the actual image size in the output file, instead it gives the output file with the current qml window size.

Basically, I follow the code while saving a QML image , but it seems to be QDeclarativeItemdeprecated in Qt5, so I choose QQuickItemwhere there is no paint in QQuickItem.

+4
1

, QQuickItem grabToImage , .

void Login::save( QQuickItem *item)
{
    auto grabResult = item->grabToImage();

    connect(grabResult.data(), &QQuickItemGrabResult::ready, [=]() {
        grabResult->saveToFile("C:/Users/haris/Desktop/output.png");
        //grabResult->image() gives the QImage associated if you want to use it directly in the program
    });
}

lambdas:

void Login::save( QQuickItem *item)
{
    auto grabResult = item->grabToImage();

    /* Need to store grabResult somewhere persistent to avoid the SharedPointer mechanism from deleting it */
    ...

    connect(grabResult.data(), SIGNAL(ready()), this, SLOT(onAsynchroneousImageLoaded()));
}

void Login::onAsynchroneousImageLoaded() {
    auto grabResult = qobject_cast<QQuickItemGrabResult*>(sender());
    if (grabResult) {
        grabResult->saveToFile("C:/Users/haris/Desktop/output.png");
    } else {
        //something went wrong
    }
});
+7

All Articles