Copying image to clipboard fails



  • Hi everybody,
    For my application, I try to copy an image to the clipboard. The image is loaded successfully to the QImage, but calling setImage() on the clipboard does simply nothing. Here is a simple compileable example, and you can get a tar containing all of these files here. Does anybody know what I am doing wrong?

    // clipboard.pro
    
    QT += core gui widgets
    
    TARGET = Clipboard
    TEMPLATE = app
    
    SOURCES += main.cpp\
            mainwindow.cpp
    
    HEADERS  += mainwindow.h
    
    RESOURCES += image.qrc
    
    // main.cpp
    
    #include "mainwindow.h"
    #include <QApplication>
    
    int main(int argc, char *argv[]) {
    
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        return a.exec();
    }
    
    // mainwindow.h
    
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include <QHBoxLayout>
    #include <QPushButton>
    #include <QApplication>
    #include <QClipboard>
    
    class MainWindow : public QMainWindow {
    
        Q_OBJECT
    
    public:
        MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private slots:
        void copy();
    };
    
    #endif // MAINWINDOW_H
    
    // mainwindow.cpp
    
    #include "mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    
        QWidget *center = new QWidget;
        this->setCentralWidget(center);
        QHBoxLayout *lay = new QHBoxLayout;
        center->setLayout(lay);
        QPushButton *but = new QPushButton("Copy");
        lay->addWidget(but);
        connect(but, &QPushButton::clicked, this, &MainWindow::copy);
    
    }
    
    void MainWindow::copy() {
    
        QImage img("image.jpg");
    
        QApplication::clipboard()->setImage(img, QClipboard::Clipboard);
        QApplication::clipboard()->setImage(img, QClipboard::Selection);
    
    }
    
    MainWindow::~MainWindow() { }
    

    image.jpg
    image


  • Lifetime Qt Champion

    Hi,

    What version of Qt are you using ? On what platform ?



  • I'm using Qt 5.8.0, running Arch Linux 64Bit



  • From the QClipboard docs, why not try this...
    QMimeData *data = new QMimeData;
    data->setImageData(image);
    clipboard->setMimeData(data, mode);

    or use a clipboard->setPixmap(...) make the pixmap from your image. Pixmaps always work like this for me.



  • Using QPixmap strangely worked... Thanks!


  • Lifetime Qt Champion

    Using the same code ?


Log in to reply
 

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