QML and Clipboard Interaction

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:


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

class QmlClipboardAdapter : public QObject
    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);

    QClipboard *clipboard;


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
        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.

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