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);
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With