Python 模拟鼠标拖动事件PyQt5
我正在制作一个自动点击QWebEngineView小部件的机器人 我想模拟一个鼠标拖动到那个小部件上 即:-Python 模拟鼠标拖动事件PyQt5,python,python-3.x,pyqt5,qtwebengine,Python,Python 3.x,Pyqt5,Qtwebengine,我正在制作一个自动点击QWebEngineView小部件的机器人 我想模拟一个鼠标拖动到那个小部件上 即:- 在QPoint(100100)上按鼠标左键btn 将鼠标移动到QPoint(500500) 释放鼠标左键 我尝试了此代码,但不起作用: def drag_from_to(browser_widget, x1, y1, x2, y2): for child in browser_widget.findChildren(QtWidgets.QWidget):
- 在QPoint(100100)上按鼠标左键btn
- 将鼠标移动到QPoint(500500)
- 释放鼠标左键
def drag_from_to(browser_widget, x1, y1, x2, y2):
for child in browser_widget.findChildren(QtWidgets.QWidget):
if (child.metaObject().className() == "QtWebEngineCore::RenderWidgetHostViewQtDelegateWidget"):
#I also tried sending the event to 'browser_widget' instead of 'child'
event_press = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, QtCore.QPoint(x1, y1),
QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, )
QtCore.QCoreApplication.postEvent(child, event_press)
event_move = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, QtCore.QPoint(x2, y2),
QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, )
QtCore.QCoreApplication.postEvent(child, event_move)
event_release = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, QtCore.QPoint(x2, y2),
QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, )
QtCore.QCoreApplication.postEvent(child, event_release)
return
编辑:我还尝试了QTest.mouseMove()。。。它实际上移动了鼠标光标。。。但是,我想让机器人在后台运行。。。我希望用户能够在Bot运行时使用他的计算机经过一些测试,我找到了解决方案:- 发布新QEvent.MouseMove后,我必须暂停代码执行至少1毫秒,我还必须将该事件顺序发送到两点之间的每一点[例如:将鼠标从QPoint(x1,y1)拖动到QPoint(x2,y2)] 以下是工作代码:
def wait(ms): QTest.qWait(ms) #pauses the code without freezing the UI
def getIntEquidistantPoints(x1, y1, x2, y2):
n = int(((((x2 - x1 )**2) + ((y2-y1)**2))**0.5))
def lerp(v0, v1, i): return v0 + i * (v1 - v0)
return [(int(x), int(y)) for x,y in [(lerp(x1,x2,1./n*i), lerp(y1,y2,1./n*i)) for i in range(n+1)]]
def drag_from_to(browser_widget, x1, y1, x2, y2):
x1 = int(x1);y1 = int(y1);x2 = int(x2);y2 = int(y2)
for child in browser_widget.findChildren(QtWidgets.QWidget):
if (child.metaObject().className() == "QtWebEngineCore::RenderWidgetHostViewQtDelegateWidget"):
event_press = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, QtCore.QPoint(x1, y1),
QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, )
QtCore.QCoreApplication.postEvent(child, event_press)
for p in getIntEquidistantPoints(x1, y1, x2, y2):
QtCore.QCoreApplication.postEvent(child,
QMouseEvent(QEvent.MouseMove,
QtCore.QPoint(p[0], p[1]),
Qt.NoButton,
Qt.MouseButtons(Qt.LeftButton),
Qt.NoModifier)); wait(1)
event_release = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, QtCore.QPoint(x2, y2),
QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, )
QtCore.QCoreApplication.postEvent(child, event_release)
这回答了你的问题吗?不,QTest.mouseMove()实际上移动鼠标光标。。。我想让机器人在后台运行。。。我希望用户能够在Bot运行时使用他的计算机