Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save QML image inside c++

Tags:

c++

qt

qml

I am trying to display 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 login class saving image like,

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 am getting the correct width and height of the image inside c++ class, but the problem is I cannot find a way to save the image item from QQuickItem.

Right now I am saving the image by grabing the window, which actually not giving the actual image size on output file, instead giving output file with current qml window size.

Basically I am following the code here saving QML image but it seems QDeclarativeItem is deprecated in Qt5, so I choose QQuickItem where as there is no paint option in QQuickItem.

like image 900
Haris Avatar asked Dec 18 '22 16:12

Haris


1 Answers

Fortunately QQuickItem has a convenient grabToImage function which does that.

void Login::save( QQuickItem *item)
{
    QSharedPointer<const QQuickItemGrabResult> 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
    });
}

Alternate solution without using lambdas:

void Login::save( QQuickItem *item)
{
    QSharedPointer<const QQuickItemGrabResult> 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<const QQuickItemGrabResult*>(sender());
    if (grabResult) {
        grabResult->saveToFile("C:/Users/haris/Desktop/output.png");
    } else {
        //something went wrong
    }
});
like image 125
coyotte508 Avatar answered Dec 24 '22 01:12

coyotte508