Filtering Mouse clicks in Qt within a class

3.5k Views Asked by At

I want to be able to enable and disable filtering mouse clicks on my entire QMainWindow by pressing a button or a key which will cause filtering to start. I want to enable the event filter from inside a class, QMainWindow.

I want to be able to have a eventfilter inside my class we can call MyWindow, from what i've found i'm supposed to make a new class MouseFilter, redefine eventFilter(QObject* object,QEvent* event) and install it on myWindow

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    MyWindow w;
    w.installEventFilter(new MouseFilter());
    w.show();
    return a.exec();
}

Is there a way I can implement the event filter from inside my object?


Solution

I think I may have been over-complicating things. It as simple as subclassing mousePressEvent.

void MouseFilter::mousePressEvent(QMouseEvent * event){
    if(event->button() == Qt::RightButton){
        qDebug() << "Right-o";
    }
}
2

There are 2 best solutions below

1
On BEST ANSWER

I think what you're looking for is the mousePressEvent which you can override from within MyWindow

Cheers, Rostislav.

0
On

An event filter is used to filter events on their way to another object. An event handler allows you implement event handling logic. An event filter is also an event handler, but it works by intercepting events, bound to be received by other objects, and decide whether and how to pass through to the destination.

What you want to do sounds like you are only looking to implement an event handler. So no event filter is necessary.

An event filter is useful when you want to block or translate events, or to alter the behavior of some object whose event handling you can't or don't want to override.