pythonuser-interfacepyqtpyqt5qwidget

Implement dragMoveEvent on QWidget in pyqt5?


does anyone know how I can implement the dragMove event on my QWidget? So basically what I want is to move my mouse over the Widget hold down my mouse button and drag it. While dragging, the widget should not be moved it should only capture the mouse coordinates while the mouse is pressed.

I have already googled and just find some drag and drop tutorials where they have dragged something into a widget etc. like text. This wasn't really helpful.


Solution

  • This has got nothing to do with dragging. What you actually need to do is enable mouse-tracking and then monitor mouse-move events.

    Here's a simple demo:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class Window(QtWidgets.QWidget):
        def __init__(self):
            super(Window, self).__init__()
            self.setMouseTracking(True)
    
        def mouseMoveEvent(self, event):
            if event.buttons() & QtCore.Qt.LeftButton:
                print(event.globalPos().x(), event.globalPos().y())
    
    if __name__ == '__main__':
    
        import sys
        app = QtWidgets.QApplication(sys.argv)
        window = Window()
        window.setGeometry(500, 150, 100, 100)
        window.show()
        sys.exit(app.exec_())