elcuco
elcuco

Reputation: 9208

Cut a file to be pasted in a file manager

I want to put a file in the OS clipboard. I am using Qt6. The windows code works, the Unix code is failing. The file is copied, and the original file is left.

    auto clipboard = QApplication::clipboard();
    auto mimeData = new QMimeData();
    auto urls = QList<QUrl>();

    urls.append(QUrl::fromLocalFile(selectedFilePath));
    mimeData->setUrls(urls);
#if defined(Q_OS_MAC) || defined(Q_OS_UNIX) || defined(Q_OS_LINUX)
    mimeData->setData("application/x-cut-operation", QByteArray("true"));
#elif defined(Q_OS_WIN)
    // 2 for cut and 5 for copy
    int dropEffect = 2;
    QByteArray dataForClipboard;
    QDataStream stream(&dataForClipboard, QIODevice::WriteOnly);
    stream.setByteOrder(QDataStream::LittleEndian);
    stream << dropEffect;
    mimeData->setData("Preferred DropEffect", dataForClipboard);
    // Should catch: Q_OS_FREEBSD, Q_OS_NETBSD, Q_OS_OPENBSD, and Q_OS_LINUX
#else
    qWarning() << "Cut operation is not supported on this platform.";
#endif
    clipboard->setMimeData(mimeData);

See also cut and paste clipboard exchange between Qt application and Windows Explorer

EDIT:

The following code enables copy on plasma6. Still no cut.

   // https://stackoverflow.com/questions/32612779/how-to-copy-local-file-to-qclipboard-in-gnome
    QByteArray gnomeFormat =
        QByteArray("cut\n").append(QUrl::fromLocalFile(selectedFilePath).toEncoded());
    mimeData->setData("x-special/gnome-copied-files", gnomeFormat);

Upvotes: 0

Views: 63

Answers (1)

Jens
Jens

Reputation: 6329

To my knowledge, Linux does not have the concept of copying files between applications (this is not needed, as the shell only needs copying and pasting of texts, having a graphic file manager is for Windows dummies only).

If you are using X11 as a GUI to Linux, then the documentation of Qt says this:

Since there is no standard way to copy and paste files between applications on X11, various MIME types and conventions are currently in use. For instance, Nautilus expects files to be supplied with a x-special/gnome-copied-files MIME type with data beginning with the cut/copy action, a newline character, and the URL of the file.

EDIT: These mime types only work on GMOME file managers obviously. For different desktops, you might try:

  • KDE: replace 'x-special/gnome-copied-files' with 'x-special/KDE-copied-files'
  • MATE: replace 'x-special/gnome-copied-files' with 'x-special/mate-copied-files'
  • XFCE: replace 'x-special/gnome-copied-files' with 'x-special/mate-copied-files'

Upvotes: -1

Related Questions