View Full Version : Moving a QButton around the form using the mouse

28th September 2009, 20:11
I posted this in the newbies section as thats what I am, but since theres no replies there I'm assuming maybe its a more advanced question or maybe just people don't understand what I'm asking.

I'm a Windows programmer, so I'm used to working with Windows messages and MFC.

What I want to do, basically: An single window app with a QPushButton on it. You run the app and you can move the button around the form by clicking the left mouse button on the QPushButton and moving the mouse around. Once you release the mouse button, the QPushButton no longer cares about the mouse position.

I don't expect someone to write this for me, just some hints or advice is fine.

28th September 2009, 20:58
Hm, you could reimplement the QPushButtons mouseMoveEvent (http://doc.trolltech.com/4.5/qwidget.html#mouseMoveEvent) and call setGeometry (http://doc.trolltech.com/4.5/qwidget.html#geometry-prop) or move (http://doc.trolltech.com/4.5/qwidget.html#pos-prop) with the events position (http://doc.trolltech.com/4.5/qmouseevent.html#pos).
But I never tried anything like that, it's just an idea.

Another possibility would be to reimplement mousePressEvent (http://doc.trolltech.com/4.5/qwidget.html#mousePressEvent), start a drag with a pixmap of the button, hide the button and reimplement dropEvent (http://doc.trolltech.com/4.5/qwidget.html#dropEvent) to move it to the dropEvents position.

28th September 2009, 21:00
Widgets / buttons are usually handled by the layout.
But since you need control over it, you shouldnt set it in layout.
Next step would be to override drag events and set the position of the widget/button according to the mouse moved.
Look more into the drag events, or how to start a drag for a widget.

You may even refer code of designer !

29th September 2009, 12:57
Once upon a time I was interested in creating just what you're describing. I've got ready code on #qt IRC channel which you can find attached to this post. Good luck!

29th September 2009, 21:19
Thanks, you described it how I had done it before using just Windows code, and then piotr.dobrogost posted example code using the same method. Perfect!