How to receive mouse events for QDoubleSpinBox
-
I want to receive the mouse click event in the subClass of QDoubleSpinBox
This is my code but in the function void SumDoubleBox::mousePressEvent(QMouseEvent* event) does not get invoked when i click on the spinbox.
class SumDoubleBox : public QDoubleSpinBox { Q_OBJECT public: using QDoubleSpinBox::QDoubleSpinBox; // inherit c'tors // re-implement to keep track of default step (optional, could hard-code step in stepBy()) void setSingleStep(double val); // override to adjust step size void stepBy(int steps) override; protected: void mousePressEvent(QMouseEvent* event); public slots: void setZero(); private: double m_defaultStep = 1.0; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <SumDoubleBox.h> #include <qlineedit.h> #include <qdebug.h> void SumDoubleBox::setSingleStep(double val) { m_defaultStep = val; QDoubleSpinBox::setSingleStep(val); } // override to adjust step size void SumDoubleBox::stepBy(int steps) { // set the actual step size here double newStep = m_defaultStep; if (QApplication::queryKeyboardModifiers() & Qt::ShiftModifier) newStep *= 0.1; // be sure to call the base setSingleStep() here, otherwise redundant loop. QDoubleSpinBox::setSingleStep(newStep); QDoubleSpinBox::stepBy(steps); } void SumDoubleBox::setZero() { QDoubleSpinBox::setValue(0.0); } void SumDoubleBox::mousePressEvent(QMouseEvent* event) { qDebug() << "Mouse pressed"; }
-
@summit said in How to receive mouse events for QDoubleSpinBox:
does not get invoked when i click on the spinbox.
It does... But only if you click the spinBox Widget, not the lineEdit or something else.
If you click theup
anddown
buttons, it should printMouse pressed
(your code worked for me, at least).Add
override
to your function definition and dont forget to pass the event to the base class after you did your stuff (unless you want to interrupt that)void SumDoubleBox::mousePressEvent(QMouseEvent* event) { qDebug() << "Mouse pressed"; QDoubleSpinBox::mousePressEvent(event); }
-
@summit
Hi
you can either set your own LineEdit with mouse press override to the
spinBox.
https://doc.qt.io/qt-5/qabstractspinbox.html#setLineEditor use event filter on the LineEdit to catch the click.
https://forum.qt.io/topic/67705/capture-mouse-click-on-qlineedit -
@summit said in How to receive mouse events for QDoubleSpinBox:
Can you please guide me towards some tutorial
Why do you need a tutorial for that?
Create a QLineEdit instance and pass its pointer to setLineEdit()...