Drop image into a QLabel



  • Hi, I need to drop an external Image into a QLabel.

    I made a class called LblImage, it implements dropEvent

    @
    void dropEvent(QDropEvent event)
    {
    if (this->pixmap()->isNull()){
    if (event->mimeData()->hasImage()) {
    event->accept();
    event->setDropAction(Qt::MoveAction);
    QByteArray pieceData = event->mimeData()->data("image/
    ");
    QPixmap img;
    img.loadFromData(pieceData);
    setPixmap(img);
    } else {
    event->ignore();
    }
    }
    }
    @

    And in the constructor
    @
    setAcceptDrops(true);
    @
    setAcceptDrops(true);
    If I try to drag and drop an image it does nothing, what am I missing? Thanks!

    Edit: I'm dragging from a file manager, so I receive text, I updated the method

    @
    void dropEvent(QDropEvent event){
    if (event->mimeData()->hasImage()){
    event->accept();
    event->setDropAction(Qt::MoveAction);
    QByteArray pieceData = event->mimeData()->data("image/
    ");
    QPixmap img;
    img.loadFromData(pieceData);
    setPixmap(img);
    setText(pieceData);

        }if (event->mimeData()->hasText()){
            event->accept();
            event->setDropAction(Qt::MoveAction);
            QByteArray pieceData = event->mimeData()->data("text/plain");
            QPixmap img;
            img.load(pieceData.mid(pieceData.indexOf("file://")+7));
            setPixmap(img);
        }
        else {
            event->ignore();
        }
    
    }
    

    @

    But Still it's now loading my Image, how should I load it to the label?



  • Here is some code from my old app:
    @void ProductImage::dragEnterEvent( QDragEnterEvent* event )
    {
    if( event->mimeData()->hasImage()
    || event->mimeData()->hasFormat( "text/uri-list" ) )
    {
    event->acceptProposedAction();
    }
    }

    void ProductImage::dropEvent( QDropEvent* event )
    {
    getImagesFromMimeData( event->mimeData() );
    event->acceptProposedAction();
    }

    void ProductImage::getImagesFromMimeData( const QMimeData* mimeData )
    {
    if( mimeData->hasImage() )
    {
    addImage( QPixmap::fromImage( qvariant_cast< QImage >( mimeData->imageData() ) ) );
    }
    else if( mimeData->hasUrls() )
    {
    foreach( QUrl url, mimeData->urls() )
    {
    addImage( QPixmap( url.path() ) );
    }
    }
    }@



  • Mime type "image/*" is not valid. I'm pretty sure you have something like "image/jpeg" or the like. You can use the dropsite app from src/examples/draganddrop to look what's actually inside the drop.

    Anyways, I would use method "QMimeData::imageData() ":http://doc.qt.nokia.com/4.7/qmimedata.html#imageData to extract the image from the drop data.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.