I am trying to change the dimensions of a QPushButton subclass while anchoring a user-defined corner (not always the top left corner). The QPushButton defines a QFrame as its parent, and is free-floating in the window. When I try to change the size of the QPushButton subclass in the subclass code, I believe it is giving me trouble since the QPoints provided by mouseEvents are local. I have tried to work with the myButton->mapToGlobal(QPoint) and myButton->mapFromGlobal but I don't think I quite understand how they work. A search for examples has left me empty handed. Can anyone provide a short example?
Local (widget) coordinates are relative to the top-left corner of the widget. Global coordinates are screen coordinates. They are easily convertible, and events like QMouseEvent offer both, local (pos()) and global (globalPos()) coordinates. If you want to map from Widget A to Widget B, you can either do
const QPoint global = a->mapToGlobal( localPosInA );
const QPoint localInB = b->mapFromGlobal( global );
Or, shorter:
const QPoint localInB = a->mapTo( b, localPosInA );
Example: Say you have a top-level widget w1 at (100,110) (screen coordinates), which has a child widget w2 at (10,10) (w1 coordinates) and a mouse event in w2 at (20, 20) (w2 coordinates), then the global position of the mouse cursor is
(100,110) + (10,10) + (20,20) = (130,140) (screen coordinates)
That's w2->mapToGlobal( mousePos ).
w2->mapTo( w1, mousePos ) or, as w1 is parent of w2, w2->mapToParent( mousePos ) is
(10,10) + (20,20) = (30,30) (w1 coordinates).
It might be easiest if you convert everything to global coordinates, do the calculations there, and then map the result back to the widget i.e. context you need it in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With