简体   繁体   English

如何排除一组事件不被 QT 的事件循环处理?

[英]How to exclude a set of events from being processed by QT's event loop?

I need to be able to exclude a set of events from being processed by the event loop;我需要能够排除事件循环处理的一组事件; I am aware there are flags that can be passed onto processEvents method (eg QEventLoop::ExcludeUserInputEvents, which processes only events that are not user inputs, but leaves the user input events there for later processing), but is there a way to process only a specific subset (or, equivalently, exclude a specific subset) of events?我知道有一些标志可以传递给 processEvents 方法(例如 QEventLoop::ExcludeUserInputEvents,它只处理不是用户输入的事件,但将用户输入事件留在那里供以后处理),但是有没有办法只处理事件的特定子集(或等效地排除特定子集)? I've been able to accomplish something similar using an event filter, but the events are discarded instead of simply not processing, which is not what I want.我已经能够使用事件过滤器完成类似的事情,但事件被丢弃而不是简单地不处理,这不是我想要的。 I was not able to find a way to do that, hence this question;我找不到办法做到这一点,因此出现了这个问题; would one have to rewrite QT's internals to do that or is there some functionality for that purpose?是否必须重写 QT 的内部结构才能做到这一点,或者是否有一些功能可用于此目的? Thanks in advance!提前致谢!

At global level you can try to override QCoreApplication::notify() event handler.在全局级别,您可以尝试覆盖QCoreApplication::notify()事件处理程序。 There you can create a set of event types which you ignore.您可以在那里创建一组您忽略的事件类型。

In the following example I override QApplication and ignore all mouse click related events.在下面的示例中,我覆盖了QApplication并忽略了所有与鼠标单击相关的事件。 When clicking on the widget, there should be NO messages displayed.单击小部件时,不应显示任何消息。 If you comment-out the notify() override, debug messages will be displayed.如果您注释掉notify()覆盖,将显示调试消息。

#include <QApplication>
#include <QDebug>
#include <QWidget>

class Widget : public QWidget
{
public:
    void mousePressEvent(QMouseEvent *) override
    {
        qDebug() << "mouse button pressed";
    }
};

class Application : public QApplication
{
public:
    Application(int argc, char *argv[]) : QApplication(argc, argv)
    {
    }

    bool notify(QObject *object, QEvent *event) override
    {
        // e.g. sink for all mouse click events
        static QSet<int> ignoredEvents = { QEvent::MouseButtonPress, QEvent::MouseButtonRelease, QEvent::MouseButtonDblClick };
        if (ignoredEvents.contains(event->type()))
        {
            return true;
        }

        return QApplication::notify(object, event);
    }
};

int main(int argc, char *argv[])
{
    Application a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM