QML and Clipboard Interaction

Edit: Please make sure to look into the comments. While this is a rather old post, thankfully, still constructive comments are raised that point out important aspects. Unfortunately, my time does not permit to properly update the post nor did it permit me to play with Qt/QML for quite some time. So, I just refer to the comments below. Thanks a lot to the commenters.

The following snippets show how one can easily interact with the clipboard from QML code with the help of a tiny C++ wrapper / adapter. This code should work for all QML versions.

The C++ code is very simple and straight forward:

#ifndef QMLCLIPBOARDADAPTER_H
#define QMLCLIPBOARDADAPTER_H

#include <QApplication>
#include <QClipboard>
#include <QObject>

class QmlClipboardAdapter : public QObject
{
    Q_OBJECT
public:
    explicit QmlClipboardAdapter(QObject *parent = 0) : QObject(parent) {
        clipboard = QApplication::clipboard();
    }

    Q_INVOKABLE void setText(QString text){
        clipboard->setText(text, QClipboard::Clipboard);
        clipboard->setText(text, QClipboard::Selection);
    }

private:
    QClipboard *clipboard;
};

#endif // QMLCLIPBOARDADAPTER_H

Registration of our adapter is done as usual in the main.cpp file:

#include <QtDeclarative>
...
#include "qmlclipboardadapter.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    ...
    qmlRegisterType("meepasswords", 1, 0, "QClipboard");
    ...
}

And finally the clipboard can be used from QML code:

...
import meepasswords 1.0
...
    QClipboard{
        id: clipboard
    }
...
    onAccepted: clipboard.setText("foo")
...

Note that this implementation is a write-only clipboard. Though, modifying the above code to enable a read-write clipboard is straight forward.

 

This entry was posted in Qt/QML, Snippets and tagged , , . Bookmark the permalink.

3 Responses to QML and Clipboard Interaction

  1. lucaspcamargo says:

    It might be better to register the type as a singleton object, since we don’t ever need more than one instance of it.

  2. Alex Makarov says:

    Fix

    qmlRegisterType(“meepasswords”, 1, 0, “QClipboard”);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s