在 Qt 中跟踪鼠标坐标

2022-01-18 00:00:00 qt widget mouseevent c++ mouse-coordinates

假设我在主窗口中有一个小部件,并且只想在小部件上跟踪鼠标位置:这意味着小部件的左下角必须是本地的 (0, 0).

Let's say I have a widget in main window, and want to track mouse position ONLY on the widget: it means that left-low corner of widget must be local (0, 0).

问:我该怎么做?

附言以下函数都不是这样做的.

p.s. NON of functions below do that.

widget->mapFromGlobal(QCursor::pos()).x();
QCursor::pos()).x();
event->x();

推荐答案

恐怕你不会满意你的要求'左下必须是(0,0).在 Qt 坐标系中,(0,0) 位于左上角.如果你能接受.以下代码...

I am afraid, you won't be happy with your requirement 'lower left must be (0,0). In Qt coordinate systems (0,0) is upper left. If you can accept that. The following code...

setMouseTracking(true); // E.g. set in your constructor of your widget.

// Implement in your widget
void MainWindow::mouseMoveEvent(QMouseEvent *event){
    qDebug() << event->pos();
}

...将为您提供鼠标指针在小部件中的坐标.

...will give you the coordinates of your mouse pointer in your widget.

相关文章