0
votes

Watching the Qt source code, I can't see where the cursor shape is changed when the mouse pointer move, there is nothing in mouseMoveEvent, neither enterEvent.

What I would like to do is a widget where the mouse cursor change depending the mouse position, but without have to put fake widgets nor set a global cursor (unless it is the only solution). But before that, I want to understand how Qt manage that.

1
Let me make sure I understood correctly. You want to know how you can change the mouse cursor shape depending on the mouse position on a widget?Iuliu
yes, this is the my end, but I also want to understand how Qt do it itself (to not to have to handle it in mouse move event)hl037_
I think I have a solution for you, see my answer. Please tell if my example suites your needs.Iuliu

1 Answers

0
votes

You can implement mouseMoveEvent or install an event filter for your widget and for certain mouse positions you can change the mouse cursor using the QCuror API.

Here is an example:

CursorChange.pro:

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = CursorChange
TEMPLATE = app


SOURCES += main.cpp \
           widget.cpp

HEADERS  += widget.h

widget.h:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

protected:
    void mouseMoveEvent(QMouseEvent *event);
};

#endif // WIDGET_H

widget.cpp:

#include "widget.h"

#include <QMouseEvent>
#include <QCursor>

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    setMouseTracking(true);
}

Widget::~Widget()
{
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->pos().x() < geometry().width() / 2)
    {
        setCursor(QCursor(Qt::OpenHandCursor));
    }
    else
    {
        setCursor(QCursor(Qt::WaitCursor));
    }

    QWidget::mouseMoveEvent(event);
}

main.cpp:

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Widget w;
    w.show();

    return a.exec();
}

This way, when you hover the mouse pointer in the left half of the widget you will have a hand mouse cursor, and if you hover the mouse pointer in the right side of the widget you will get a wait mouse cursor.