Ariya Hidayat
Graphics Dojo
Posted by Ariya Hidayat
 in Graphics Dojo
 on Friday, March 20, 2009 @ 07:37

It is about time for another charm. By charm here, I mean something that you can cast to your existing code (e.g. without changing the class implementation) to get new magical functionalities. You saw the Flick Charm before, as an example.

Today we uncover the secret to make a window (usually the top-level widget) movable by mouse dragging. This trick is employed for example in applications which have custom window decoration, like Apple iTunes or Google Chrome. In these applications, the title bar is not the actual native title bar from the window system. Yet you can "grab" it and use it to move the window around. You may encounter similar behavior in many different web widgets (not in the sense of QWidget), be it Dashboard widgets, Microsoft gadgets, plasmoids, Google gadgets, and so on.

The secret is of course by (ab)using the event filter. Thus, making your window movable-by-dragging is a matter of writing the code:

DragMoveCharm charm;
charm.activateOn(window);

(At the risk of repeating myself, no code for window needs to be touched).

Any mouse events will be monitored and if they indicate the dragging, the window will be repositioned appropriately. Of course, the trick here is to apply the charm to the top-level window which serves as the outermost frame of your application. A wrong way to use it is e.g. instantiating a QWebView instance and applying there, because now the mouse can’t be used to scroll or select text.

Get the example for the usual git repository. Don’t want to use git? Just grab the snapshot archive (103 KB) and unpack it. You need either Qt 4.4 or Qt 4.5.

And here is a 30-second screencast that demonstrates the charm. Watch in on YouTube, blip.tv, or get the Ogg Theora video (3.7 MB).

5 Responses to “Moving top-level window by dragging”

» Posted by ariya
 on Friday, March 20, 2009 @ 09:37
Ariya Hidayat

According to Fredrik Höglund (KDE), for topmost window on X11, you should use _NET_WM_MOVERESIZE instead (http://standards.freedesktop.org/wm-spec/1.4/ar01s04.html#id2568642). This is also what KRunner is doing.

» Posted by Bobby
 on Friday, March 20, 2009 @ 10:36

Since the example code is under GPL license I can’t use it in my commercial application, or?

» Posted by Gabban
 on Friday, March 20, 2009 @ 11:22

It’s too simpl to post this in a blog

» Posted by deabru
 on Friday, March 20, 2009 @ 12:29

Just like bespin does. Very useful

» Posted by Vitaly
 on Saturday, March 21, 2009 @ 01:21

It’s not *that* simple if you are new to Qt. Thanks and keep ‘em coming!



© 2008 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.
All other trademarks are property of their respective owners.