模拟鼠标释放 Pyqt
Posted
技术标签:
【中文标题】模拟鼠标释放 Pyqt【英文标题】:Simulate a mouse release Pyqt 【发布时间】:2013-03-26 01:12:49 【问题描述】:如何使用 Qt.SIGNAL 模拟鼠标释放动作? 我需要在没有用户交互的情况下模拟 mouseRelease。 提前致谢!
【问题讨论】:
【参考方案1】:这是一个使用QPushButton
的clicked
信号的示例:
#!/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_())
【讨论】:
正是我想要的!很好的答案! 我尝试了完全相同的代码,但它似乎没有做任何事情。 press = QMouseEvent(QEvent.MouseButtonPress, pos, Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) print("Testing2") release = 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)【参考方案2】:你可以使用:
from PyQt4.QtTest import QTest
#(...) Where you want to release
QTest.mouseRelease(widget_to_release, Qt.LeftButton)
这将释放小部件中心的鼠标。
还有mousePress()
、mouseClick()
等的方法。但是,如果您在 Windows 上测试拖放,请注意等效的 QTest.mousePress()
会阻塞,因为 QDrag.exec_()
会阻塞。
【讨论】:
以上是关于模拟鼠标释放 Pyqt的主要内容,如果未能解决你的问题,请参考以下文章