When an object of QLabel subclass is active, how can one find if the mouse pointer is on the label and get its position if it is?
QWidegt::event() can check the event type of QEvent::WindowActivate, but it provides no information about mouse pointer position.
I then tried the following code, which verifies itself that both focusInEvent and focusOutEvent can happen. However, I still cannot get the mouse pointer position. Maybe I am missing the part of "bind enable/disable of mouse tracking to focus in and out events", or something else.
#include "mainwindow.h"
#include <QApplication>
#include <QtWidgets>
#include <QtCore>
class MyLabel : public QLabel
{
public:
MyLabel(QWidget*parent = nullptr) : QLabel(parent)
{
setMouseTracking(true);
setFocusPolicy(Qt::FocusPolicy::StrongFocus);
}
protected:
virtual void focusInEvent(QFocusEvent *ev) override
{
(void)ev;
this->setText(__PRETTY_FUNCTION__);
}
virtual void focusOutEvent(QFocusEvent *ev) override
{
(void)ev;
this->setText(__PRETTY_FUNCTION__);
}
virtual void mouseMoveEvent(QMouseEvent *ev) override
{
this->setText(QString::number(ev->pos().x()) +", " +QString::number(ev->pos().y()));
QLabel::mouseMoveEvent(ev);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyLabel w;
w.setFixedSize(400, 300);
w.show();
return a.exec();
}
setMouseTracking(true)for yourQLabelsubclass and overridemouseMoveEvent(QMouseEvent *ev)to get informed about mouse movement on your label widget and get mouse position. On top of that you could bind enable/disable of mouse tracking to focus in and out events. Therefore it's necessary to overridefocusInEvent(QFocusEvent *ev)andfocusOutEvent(QFocusEvent *ev)and set focus policy accordingly.xandyposition label text if i move the mouse on it. It also works without using/overriding the focus events.QCursor::pos()to get current cursor position if widget gets focus. After that get global position of your label widget upper left corner usingmapToGlobal(QPoint(0,0))and lower right corner usingmapToGlobal(QPoint(width(), height())). Finally check if cursor position is inside your label widgets rectangle and run an action (e.g. show tooltip).