Subnavigation

Moving top-level window by dragging

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


Blog Topics:

Comments