模拟鼠标拖动事件 PyQt5
Posted
技术标签:
【中文标题】模拟鼠标拖动事件 PyQt5【英文标题】:simulate mouse drag event PyQt5 【发布时间】:2021-06-02 19:13:27 【问题描述】:我正在制作一个自动点击 QWebEngineView 小部件的机器人。
我想模拟鼠标拖动到那个小部件
即:-
在 QPoint(100,100) 上按鼠标左键
将鼠标移动到 QPoint(500,500)
松开鼠标左键
我试过这段代码,但它不起作用:
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 在后台运行...我希望用户能够使用他的计算机当机器人运行时
【问题讨论】:
这能回答你的问题吗? How to test drag and drop behavior in PyQt? 不,QTest.mouseMove() 实际上会移动鼠标光标...我希望 Bot 在后台运行...我希望用户能够在 Bot 运行时使用他的计算机运行 【参考方案1】:经过一番测试,我找到了解决办法:-
在发布新的 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)
【讨论】:
以上是关于模拟鼠标拖动事件 PyQt5的主要内容,如果未能解决你的问题,请参考以下文章