Simulate Pyqt Mouse Release

How can I simulate a mouse action using Qt.SIGNAL? I need to simulate mouseRelease without user interaction. Thanks in advance!

+5
source share
2 answers

Here is an example using a clickedsignal QPushButton:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonSimulate = QtGui.QPushButton(self)
        self.pushButtonSimulate.setText("Simulate Mouse Release!")
        self.pushButtonSimulate.clicked.connect(self.on_pushButtonSimulate_clicked)

        self.layoutHorizontal = QtGui.QHBoxLayout(self)
        self.layoutHorizontal.addWidget(self.pushButtonSimulate)

    @QtCore.pyqtSlot()
    def on_pushButtonSimulate_clicked(self):
        mouseReleaseEvent = QtGui.QMouseEvent(
            QtCore.QEvent.MouseButtonRelease,
            self.cursor().pos(),
            QtCore.Qt.LeftButton,
            QtCore.Qt.LeftButton,
            QtCore.Qt.NoModifier,
        )

        QtCore.QCoreApplication.postEvent(self, mouseReleaseEvent)

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            print "Mouse Release"

        super(MyWindow, self).mouseReleaseEvent(event)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())
+3
source

You can use:

from PyQt4.QtTest import QTest

#(...) Where you want to release
QTest.mouseRelease(widget_to_release, Qt.LeftButton)

This will release the mouse in the center of the widget.

There are also methods for mousePress(), mouseClick()and others. However, if you are checking drag and drop in Windows, be careful that the equivalent QTest.mousePress()will block because it QDrag.exec_()blocks.

+1
source

All Articles