1

I want to implement a drag and drop functionality between two custom widgets. My understanding from this question is that I cannot use the built-in drag and drop functionality that e.g. buttons would provide, but that I need to implement mouseReleaseEvent and mousePressEvent handlers manually.

My specific goal is as follows: I have widgets of type Widget1 and Widget2, and I want that when Widget1 is dragged onto Widget2, a certain action is performed. I therefore implemented the mousePressEvent of Widget1 and the mouseReleaseEvent of Widget2.

class Widget1(QWidget):
   ...
   def mousePressEvent(self, event):
      print("Press")

class Widget2(QWidget):
   ...
   def mouseReleaseEvent(self, event):
      print("Release")

While "Press" is printed whenever I click on Widget1, "Release" is printed only after clicking on Widget2. That is, the release event is called for the same item that was clicked. How do I execute an action for the widget that the mouse was over at release?

Samufi
  • 2,465
  • 3
  • 19
  • 43
  • Once a `mousePressEvent` is captured (and not ignored) by a widget, it takes control of any other mouse event. You have to implement the `mouseReleaseEvent` event on the widget that originates the press event, or, otherwise, use an event filter. – musicamante May 23 '20 at 21:22
  • @musicamante how would I figure out on which widget the mouse is released? Would I have to compute this from the pixel position? Is there a simpler way? Would an event filter help me with that? How? – Samufi May 23 '20 at 21:54
  • 1
    You can use [`childAt`](https://doc.qt.io/qt-5/qwidget.html#childAt-1) on the top level window of the widget (via `window()`). – musicamante May 24 '20 at 16:04
  • @musicamante like self.childAt(event.pos())) given event an mousepressevent ?? – pippo1980 Jun 04 '22 at 16:37
  • 1
    @pippo1980 Yes, but not with the event `pos`: you must use the `globalPos()` with `mapFromGlobal()` on the top level widget. – musicamante Jun 04 '22 at 17:21
  • @musicamante I am using pos() on a QGroupBox inside a second QMainWindow and seems to do the expected job, I'll post a question about it for other reasons soon, first need to figure out out to return standard mousepressEvent on if else clause when rewriting def mousePressEvent(self, event): to intercept some stuff – pippo1980 Jun 04 '22 at 17:29
  • scrap the return part above def mousePressEvent(self, event) is rewritten for each widget – pippo1980 Jun 04 '22 at 18:40

0 Answers0