问题描述
我试图创建一个应用程序,鼠标移到屏幕上的某些位置,并自动点击左键。
问题是我无法点击Qt应用程序之外,所以我通过使应用程序透明的鼠标点击,并使其使用此代码,使其全屏:
I am trying to make an application where the mouse goes to certain locations on screen and automatically clicks left button.The problem is I cant click outside the Qt application so I made a workaround by making the application transparent to mouse clicks and making it full screen using this code:
int x = 800;
int y = 500;
this->setWindowFlags(Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint|Qt::ToolTip);
this->setAttribute(Qt::WA_TranslucentBackground);
this->setAttribute( Qt::WA_TransparentForMouseEvents);
QCursor::setPos(x,y);
qDebug()<<QCursor::pos();
QWidget *d = QApplication::desktop()->screen();
QMouseEvent MouseEvent(QEvent::MouseButtonPress, QCursor::pos(),Qt::LeftButton,Qt::LeftButton, Qt::NoModifier);
QApplication::sendEvent(d, &MouseEvent);
QApplication::sendEvent(d, &MouseEvent);
鼠标光标移动到所需位置,但点击不起作用。
我也尝试替换Qt类处理鼠标事件和使用Windows API,因为我真的不需要跨平台的应用程序,但我陷入了同一个点。
The mouse cursor moves to the desired location but the clicking doesn't work.I also tried replacing the Qt class for handling mouse events and use windows API since I don't really need cross-platform application but I am getting stuck at the same point.
推荐答案
我知道这有点晚了,但有办法做你想要的。一般来说,创建或模拟用户界面事件只用于自动测试。
I know that this is a bit late, but there are ways to do what you want. In general creating or simulating user interface events is used only for automated testing.
如果你想要一些计算或算法的结果,结果来自一个软件,而不是自动化其UI。您可以查看它是否有一个记录的API,您可以调用它调用的相同的Web服务,您可以链接到它所使用的相同的库,或者您可以复制它使用的算法。
If you want the results of some calculation or algorithm there is almost always a better to get it desired result from a piece of software other than automating its UI. You can see if it has a documented API, you can call the same web services it calls, you can link against the same libraries it does or you can duplicate algorithms it uses.
如果这些都不可接受,那么您应该查看。
If none of these are acceptable then you should probably look at the QT5 tutorials on automated testing.
特别是。对于单击名为的函数的函数有两个重载。
Specifically the QTest Namespace. There are two overloads for functions that click the mouse called QTEST::mouseClick.
我认为这可能会做你想要的:
I think this might do what you want:
#include <QTest>
// class and function declarations removed here
QTest::mouseClick(d, Qt::LeftButton, Qt::NoModifier, QPoint(x,y));
这篇关于Qt5 C ++自动鼠标点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!