How to create a moveable widget in Q

First, it should be noted that for experienced Qt people, this is probably so basic it's hard to think down to this level. For newbies and people who aren't familiar with object orientated software, these things take a while to understand. This really is for noobs and the hard of thinking like me.

I've been struggling to work out how to make a widget movable by the user with Qt and Qt creator. The examples given by Nokia are much more complicated than what I was trying to achieve and this isn't a drag and drop exercise - the kind that seems to be plentiful on line. All I wanted to do was have the user left click on a widget and have her move it, but moving the mouse, to where she wanted on the screen, within the form the widgit was placed on.

It turns out, that it's actually pretty simple to achieve by creating your own widget, based on an existing widget (I think this may be called subclassing), by redefining some of the existing widget's routines.

The widget itself will respond to mouse events, so by using existing routines such as mousePressEvent and just writing your own code to go in these routines, it's relatively straightforward to create your own user movable widget. What took me a while to realise was that, rather than needing routines in the form (or parent widget) to deal with the mouse click on the widget you want to make user movable, the routines need to be made in the widget itself. Once I had understood that concept, things became much easier. It just took me quite some time to discover that.

If anyone does happen to read this and find I have done things in a clumsy fashion, or broken good C++ programming techniques I would be happy to be corrected. What I don't want to be inundated with is people complaining about the completely legitimate Whitesmiths coding style or slightly different ways of doing it that aren't better, but just different. :~) I very much want to learn about mistakes I made, as well as they are done in a polite and constructive manner.

Download the archive here and examine the contents. It was written for Linux, but for those running virus loving or locked down, DRM ridden Unix operating systems, I think it should be completely portable.

in rButton.h you'll see that the class rButton is based on QPushButton, one of the standard Qt widgets. You'll then see three routines that already exist and one extra one. Also, there are a few global variables which might well be very naughty; if there are better ways to do this, please let me know! You can load this into the excellent Qt creator and see the main ui form and mainwindow.cpp that creates a couple of draggable buttons on the ui form.

In rButton.cpp, the routines are well commented and (hopefully) easy enough to follow without having to go over it again here.

Please contact me at code@apostrophe.co.uk for any improvements, mistakes or questions. Hope this helps other noobs. :~)