Tracking mouse coordinates in Qt

后端 未结 2 1723
日久生厌
日久生厌 2021-01-06 04:49

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

2条回答
  •  借酒劲吻你
    2021-01-06 05:46

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

提交回复
热议问题