Search code examples
qtmouseeventqscrollareamouse-positionmousepress

How to get mouse press position relative to QScrollArea's widget


If I have a wide widget in a QScrollArea, and I press the mouse on it, then I get a mouse position (in mousePressEvent()) relative to the scroll area (if I scroll, it changes).

How can I get the mouse position relative to that wide widget inside the scroll area?

I tried to use a combination of functions mapTo(), parentWidget(), viewport() and had no success.


Solution

  • At the moment I've got three similiar ways that work quite fine for me.

    class MyWidget : public QScrollArea
    {
    // ...
    };
    
    void MyWidget::mousePressEvent(QMouseEvent *event)
    {
        qDebug() << widget()->mapFromGlobal(QCursor::pos());     // 1
        qDebug() << widget()->mapFrom(viewport(), event->pos()); // 2
        qDebug() << widget()->mapFromParent(event->pos());       // 3
    }