0

I want the mouse to be "stuck" inside the QScrollArea while I'm dragging custom widget. I made the QScrollArea a subclass called MyScrollArea so I could reimplement the event mouseMoveEvent. This is MyScrollArea subclass:

myscrollarea.h

#ifndef MYSCROLLAREA_H
#define MYSCROLLAREA_H

#include <QScrollArea>
#include <QDebug>
#include <QtGui>

class MyScrollArea : public QScrollArea
{
    Q_OBJECT
public:
    explicit MyScrollArea(QWidget *parent = 0);

signals:
    void changeLabel(QString);

public slots:

protected:
    void leaveEvent(QEvent *event);

    void mouseMoveEvent(QMouseEvent *event);

private:
    int mouseX, mouseY;
};

#endif // MYSCROLLAREA_H

myscrollarea.cpp

#include "myscrollarea.h"

MyScrollArea::MyScrollArea(QWidget *parent)
    : QScrollArea(parent)
{
    this->setMouseTracking(true);
    mouseX = 0;
    mouseY = 0;
}

void MyScrollArea::leaveEvent(QEvent *event)
{
    qDebug() << "LEFT!";
}

void MyScrollArea::mouseMoveEvent(QMouseEvent *event)
{
    mouseX = event->x();
    mouseY = event->y();
    event->accept();
    emit changeLabel(QString::number(mouseX) + ", " + QString::number(mouseY));
}

Even though the mouse tracking is set to true, I only manage to get the mouseMoveEvent when a button is held.

My question is:

  1. How do I make mouseMoveEvent trigger in all movements?
  2. How do I set the cursor to the last position (inside the "QScrollArea") when he is dragging the custom widget I created?
andseg
  • 658
  • 1
  • 9
  • 26

1 Answers1

0

What about using EventFilter? Steps:

Install an event filter in your widget:

this->setMouseTracking(true);
this->installEventFilter(this);

Reimplement the eventFilter function:

bool MyScrollArea::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == this) {
        if(event->type() == QEvent::MouseMove) {
             QMouseEvent *mEvent = (QMouseEvent*)event;
             // Use something like the viewPortSize to handle if the pos event is inside
             if (over) { 
                   // Mouse over Widget
             } else {
                  // Mouse outside
             }
        }
    } else {
        return QScrollArea::eventFilter(obj, event);
    }
}
mohabouje
  • 3,867
  • 2
  • 14
  • 28
  • This is a good idea. Just as pointed by eyllanesc. But the I don't know if the `event->type()` is a `QEvent::MouseMove` because `mouseTracking` is not working properly. Again, this solves my second problem, but not the first one. – andseg Feb 23 '17 at 18:01