Mouse Move Example

After to install event filter, we can get first mouseMoveEvent.

My example is moving a QLabel in a QWidget by mouse.

Creating my label and installing event filter:

ExampleApplication::ExampleApplication(QWidget *parent)
: QMainWindow(parent),
  mCursorX(0),
  mCursorY(0)
  {
     ui.setupUi(this);
     lbl = new QLabel("Hello!", this);
     lbl->setFixedWidth(80);
     lbl->setFixedHeight(35);

     installEventFilter(this);
}

Overriding eventFilterFunction on header file:

virtual bool eventFilter(QObject *object, QEvent *ev) override;

private:
Ui::ExampleApplicationClass ui;
int mCursorX;
int mCursorY;
QLabel* lbl;

 

 

Getting mouseMove event on eventFilterFunction:

bool ExampleApplication::eventFilter(QObject *object, QEvent *ev)
{
       if (ev->type() == QEvent::MouseMove)
       {
             QMouseEvent* mouseEvent = (QMouseEvent*)ev;
             if (mouseEvent->type() == QMouseEvent::MouseMove)
            {
                mCursorX = mouseEvent->x();
                mCursorY = mouseEvent->y();

                lbl->setGeometry(mCursorX, mCursorY, 80, 35); //80:width 35:height
             }
       }
       return false;
}

Leave a Reply

Your email address will not be published. Required fields are marked *