mrk_brn
mrk_brn

Reputation: 39

Qt: get mouse pressed event even if a button is pressed

I need to simply detect when the right button is pressed or released in my Qt5/C++ application every moment.

So far I have coded these functions:

void test::mousePressEvent(QMouseEvent *ev){
    if(ev->buttons() == Qt::LeftButton){
        qDebug() << "Left pressed";
        ui->forceBar->setValue( 100 );
    }

}

void test::mouseReleaseEvent(QMouseEvent *ev){
    if(ev->button() == Qt::LeftButton){
        ui->forceBar->setValue( 50 );
        qDebug() << "Left released";
    }

They work fine only if the click is not on a pushbuttontest. The problem is that if the click happens on a pushbutton, I don't get the event.

Upvotes: 2

Views: 11065

Answers (1)

Hariprasad
Hariprasad

Reputation: 3640

You have to derive from QPushButton and override these event handlers.

class MyButton : public QPushButton
{
   protected:
       virtual void mousePressEvent(QMouseEvent* event);
       virtual void mouseReleaseEvent(QMouseEvent* event);
};


void MyButton::mousePressEvent(QMouseEvent *ev){
    if(ev->buttons() == Qt::LeftButton){
        qDebug() << "Left pressed";
        ui->forceBar->setValue( 100 );
    }

}

void MyButton::mouseReleaseEvent(QMouseEvent *ev){
    if(ev->button() == Qt::LeftButton){
        ui->forceBar->setValue( 50 );
        qDebug() << "Left released";
    }

Then, use this button as pushbuttontest:

QPushButton* pushbuttontest = new MyButton();

Or, if you want to have a common event handler for many widgets, you can use event filters:

class test : public QWidget // the widget in which you want to capture all events
{
public:
   bool eventFilter(QObject *watched, QEvent *e);
private:
   QPushButton* pushbuttontest;
   QLabel *myLabel;
};

bool test::eventFilter(QObject *watched, QEvent *e)
{
  if (e->type() == QEvent::MouseButtonPress)) 
   {    
      QMouseEvent* ev = (QMouseEvent*)e;
      if(ev->buttons() == Qt::LeftButton){
        qDebug() << "Left pressed";
        ui->forceBar->setValue( 100 );
    }
  }
else if (e->type() == QEvent::MouseButtonRelease)
  {
      QMouseEvent* ev = (QMouseEvent*)e;
      if(ev->buttons() == Qt::LeftButton){
        qDebug() << "Left released";
        ui->forceBar->setValue( 100 );
    }
  }
   return false;// return true if you are finished handling the event. So, the default event handler will not be called.
}

Then, install the eventFilter to the widgets you want:

pushbuttontest = new QPushButton();
pushbuttontest->instalEventFilter(this); // this is the test class object which has our event filter code.
myLabel = new QLabel();
myLabel->installEventFilter(this);

etc.

Please note that I have not compiled this code. It may not work straight away.

For more info : http://qt-project.org/doc/qt-4.8/eventsandfilters.html

Upvotes: 3

Related Questions