Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QQuickImage convert to QImage

I've been using QZXing to decode QR code, my QML looks like this

Image{ 
    width:300
    height:300
    id:imageToDecode
    source:"qr.jpg"
    cache: true
}

and when i pass it into C++ file, it has to be converted into a QImage type, in the code the original coder wrote like this

QGraphicsItem *item = qobject_cast<QGraphicsItem*>(imageObj);

and then use QGraphicsItem to construct a QImage,however this will always return 0 after conversion, since QGraphicsItem does not inherit QObject

straight conversion like

QImage*item = qobject_cast<QImage*>(imageToDecode);

will not work for same reason,ive been using

imageObj->inherits("objectName");

to test which one it can be converted to, but there is none i can find my point is to convert QML Image into QImage.

like image 592
user2703750 Avatar asked Oct 20 '25 05:10

user2703750


2 Answers

If you are using Qt5 or greater and QtQuick 2.0 or greater you can't render the Image element to QGraphicsItem or anything related to QGraphics since from Qt5 the backend for QML is scenegraph and not QGraphics. So now going forward with Qt5.3 and you if access the Image element in C++, it will be casted to a QQuickImage internally, but still you can't extract image from Image element since QQuickImage has not been made public yet. Ref. http://qt-project.org/forums/viewthread/32767

The solution they have proposed for now is to use QQuickImageProvider.

like image 158
astre Avatar answered Oct 21 '25 19:10

astre


I found something that may (or may not) be a workaround to this issue.

Within the Image that is assigned the preview source, I call grabToImage() in order to create a QQuickItemGrabResult object and then in C++, I call the image() function on that object. It seems to work.

QML

Image {
  id:imageToDecode
  MouseArea {
    anchors.fill:parent
    onClicked: parent.grabToImage(function(result)
      decoder.decodeImageQML(result); })
    }
 }

C++

QImage ImageHandler::extractQImage(QObject *imageObj,
                     const double offsetX, const double offsetY,
                     const double width, const double height)
{
    QQuickItemGrabResult *item = 0;
    item = qobject_cast<QQuickItemGrabResult*>(imageObj);
    QImage item_image(item->image());
    ....
}
like image 27
Charles Thomas Avatar answered Oct 21 '25 20:10

Charles Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!