模拟鼠标拖动事件PyQt5



我正在制作一个自动点击QWebEngineView小部件的机器人。

我想模拟鼠标拖动到小部件

即:-

  • 在QPoint(100100(上按下鼠标左键

  • 将鼠标移动到QPoint(500500(

  • 释放鼠标左键btn

我试过这个代码,但它不起作用:

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之后,我必须暂停代码执行至少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)

最新更新