Qt Get Mouse Position
In Qt, you can use the QCursor class to retrieve the current position of the mouse. The specific steps are as follows:
- 导入QCursor类:
- import QCursor
- Use the QCursor::pos() method to obtain the current global position of the mouse.
- Get the current position of the cursor and store it in a variable called cursorPos.
The QPoint class represents the coordinates of a point, with the x() method returning the x-coordinate of the point and the y() method returning the y-coordinate of the point.
For example, the following code demonstrates how to retrieve and display the position of the mouse:
#include <QApplication>
#include <QCursor>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 获取鼠标当前位置
QPoint cursorPos = QCursor::pos();
// 输出鼠标位置的x和y坐标
qDebug() << "Mouse Position: (" << cursorPos.x() << ", " << cursorPos.y() << ")";
return a.exec();
}