2013-03-26 114 views

回答

3

下面是一個使用QPushButtonclicked信號的例子:

#!/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_()) 
+1

正是我在找的東西!傑出的答案! – karensantana 2013-03-29 03:00:00

+0

我嘗試了完全相同的代碼,但它似乎沒有做任何事情。 按= QMouseEvent(QEvent.MouseButtonPress,POS,Qt.LeftButton, Qt.LeftButton,Qt.NoModifier) 打印( 「Testing2」) 釋放= QMouseEvent(QEvent.MouseButtonRelease,POS, Qt.LeftButton,Qt.LeftButton ,Qt.NoModifier) print(「Testing3」) QApplication.postEvent(self.view,press) time.sleep(1) QApplication.postEvent(self.view,release) – d34th4ck3r 2017-06-28 10:59:34

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_()阻止。