Search code examples
qtdrag-and-dropmimeqgraphicsviewqlistwidget

Qt: send QPixmap in QDrag's QMimeData?


I create a drag object from a QListWidgetItem. I can send text as mime data in this drag object.

How can I send a pixmap and retrieve it from the mime data? Would it even be possible to create a QGraphicsItem and retrieve it?

I try to drag & drop from the QListWidget into a QGraphicsView.


Solution

  • There are multiple ways to send a QPixmap through QMimeData:

    1. by encoding it into a file format such as PNG and sending that with mime-type image/png (QMimeData has built-in support for that, cf. QMimeData::imageData()).
    2. by serialising the QPixmap into a QByteArray using a QDataStream and sending the serialisation under an app-specific mime-type application/x-app-name.
    3. by writing the image data to a file on disk and sending a file-URL for it with mime-type text/uri-list (QMimeData has built-in support for this, cf. QMimeData::urls()). This allows to drag these images onto a file manager or the desktop.
    4. similar to (2) above, you can also create a QGraphicsItem, stuff its address into a QByteArray and send that under an app-specific mime-type. This doesn't work if the drag ends in another process, of course (the receiving site can test, because QDragEvent::source() returns 0 in that case), and it requires special care to handle the graphic item's lifetime.

    Seeing as QMimeData allows you to pass several formats at once, these options are non-exclusive. You should, however, sort the formats you return from your reimplementation of QMimeData::formats() in order of decreasing specificity, i.e. your app-private formats come first, and text/uri-list comes last.