C++ 在 Qt 中跟踪鼠标坐标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18551387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:01:03  来源:igfitidea点击:

Tracking mouse coordinates in Qt

c++qtwidgetmouseeventmouse-coordinates

提问by Mike

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).

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

Q: How can I do this?

问:我该怎么做?

p.s. NON of functions below do that.

ps NON 下面的函数是这样做的。

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

回答by Greenflow

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...

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

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.

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

回答by Reinstate Monica

If all you want to do is to report position of the mouse in coordinates as if the widget's lower-left corner was (0,0) and Y was ascending when going up, then the code below does it. I think the reason for wanting such code is misguided, though, since coordinates of everything else within said widget don't work this way. So why would you want it, I can't fathom, but here you go.

如果您想要做的只是在坐标中报告鼠标的位置,就好像小部件的左下角是 (0,0) 并且 Y 在上升时是上升的,那么下面的代码就可以做到。但是,我认为需要此类代码的原因是错误的,因为所述小部件中其他所有内容的坐标不能以这种方式工作。所以你为什么要它,我无法理解,但你去吧。

#include <QtWidgets>

class Window : public QLabel {
public:
    Window() {
        setMouseTracking(true);
        setMinimumSize(100, 100);
    }
    void mouseMoveEvent(QMouseEvent *ev) override {
        // vvv That's where the magic happens
        QTransform t;
        t.scale(1, -1);
        t.translate(0, -height()+1);
        QPoint pos = ev->pos() * t;
        // ^^^
        setText(QStringLiteral("%1, %2").arg(pos.x()).arg(pos.y()));
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Window w;
    w.show();
    return a.exec();
}