Search code examples
qtinheritancemouseeventmouse-positionqmouseevent

How can I access protected member in QMouseEvent to get a float value of mouse position ? [Qt developers]


QMouseEvent stores an integer value of the mouse position. However, it has a protect member "s" which stores a float value of the mouse position. How can I get the float value?

I have tried inheriting the QMouseEvent, but unfortunately I get this error message all the time.

error: C2511: 'QMouseEventF::QMouseEventF(QWidget *)' : overloaded member function not found in 'QMouseEventF'

This is my header file:

#ifndef QMOUSEEVENTF_H
#define QMOUSEEVENTF_H

#include<QMouseEvent>

class QMouseEventF : QMouseEvent
{
    Q_OBJECT

    public:
    QMouseEventF(QObject* parent = 0);

    ~QMouseEventF();
    qreal GetX();

};

#endif // QMOUSEEVENTF_H

And here is the inherited class:

#include "qmouseeventf.h"


QMouseEventF::QMouseEventF(QWidget *parent ): QMouseEvent(parent)
{

}


QMouseEventF::~QMouseEventF()
{

}


qreal QMouseEventF::GetX()
{
    return this->s.rx();
}

Solution

  • For one, you have a different signature between header and source file because the header constructor is different than the source constructor. QMouseEvent does not inherit from QObject or QWidget.

    Second, QMouseEvent does not take a QWidget * for a constructor.

    Third, there is no need for the Q_OBJECT macro in the header.

    Those are the reasons for correctness of the code. To answer your original question, it wouldn't make sense to use a float value since the integer value is what the mouse events operate with for pixel coordinates. If you need to convert it to float, do so yourself by casting.