6

如何使用 Qt.SIGNAL 模拟鼠标释放动作?我需要在没有用户交互的情况下模拟 mouseRelease。提前致谢!

4

2 回答 2

4

clicked这是使用 a 的信号的示例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_())
于 2013-03-26T09:03:22.757 回答
1

您可以使用:

from PyQt4.QtTest import QTest

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

这将释放小部件中心的鼠标。

还有用于mousePress()mouseClick()和其他的方法。但是,如果您在 Windows 上测试拖放,请注意等效项QTest.mousePress()会阻塞,因为会QDrag.exec_()阻塞。

于 2015-01-13T03:46:46.063 回答