Tracking mouse coordinates in Qt

空扰寡人 提交于 2019-11-30 17:20:17

问题


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

Q: How can I do this?

p.s. NON of functions below do that.

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

回答1:


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.




回答2:


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.

#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();
}


来源:https://stackoverflow.com/questions/18551387/tracking-mouse-coordinates-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!