QClipboard wrapper for QML

by markg85

Hi,

It’s not the first Qt class that i’m making usable in QML and will certainly not be the last one. Even better would be singleton components because you really don’t want two of these components in one application, something that is possible in Qt5 if i’m correct.

Note: It has been suggested that i make this as a plasma service. I do wonder, what’s the benefit over a component? And how to even make a service? Making this wrapper class is really easy, is it even easier with services? Making this wrapper was really easy and only took a few hours.

Without further delay, here is the “Clipboard” QML component free for you to use however you like.
clipboard.h

And the clipboard.cpp file:

You obviously have to register the class in QML as well. Look in my other posts if you don’t know how to do that.

Now using this class needs a bit of documentation. First, you have to add it to QML which is as simple as adding:

Lets say you want to paste the content of the clipboard. For that i take my Shortcut element as example, look at the following code:

This happens to be an example for CTRL+V (pasting). clip.paste is where the magic happens. All you have to do is provide a location (with the protocol in front of it like “file://”). Then the files that are on the clipboard will be put on that location.

If you want to copy/cut files you have to go through some more trouble. This “trouble” is there because QML doesn’t properly allow arrays to be filled after they have been defined in “property variant someArray”. This has been resolved in Qt 5 where “property var someArray” works just as you would expect from a javascript array.

So, in the above Clipboard QML component you have one function to fill the url: clip.addUrl(file:///your/url/to/anything/). If you have multiple urls you have to add them all – one by one.
clip.addUrl(file:///your/url/to/anything/one)
clip.addUrl(file:///your/url/to/anything/two)
clip.addUrl(file:///your/url/to/anything/three)

Another function you have is clip.urlList() which just spits out your url list. There is no remove/clear/anything else for the url container.
Once you’re done adding url entries you call clip.cut() or clip.copy(), depending on what you want to do. After that point the files (urls actually) will have been placed on the clipboard and the url list will be cleared ready for the next job.

That’s about all there is to know for this wrapper.