本文介绍了了解其他课程发生的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类:

typedef std::shared_ptr<AdaptedWidget> window_ptr;

class WindowManager
{
public:
...
private:
    std::stack<window_ptr> m_windowsStack;
}

class AdaptedWidget: public QWidget
{
    Q_OBJECT
public:
    AdaptedWidget(AdaptedWidget *parent = 0);
    bool event(QEvent *event);
};

bool AdaptedWidget::event(QEvent *event)
{
    if (event->type() == QEvent::NonClientAreaMouseButtonPress ||
        event->type() == QEvent::MouseButtonPress)
    {
        qDebug() << "mainwindwo press";
    }
    return QWidget::event(event);
}

我需要获取有关中发生的事件的信息AdaptedWidget 对象从我的 WindowManager 对象,我该怎么做?

I need to get information about events that happen in AdaptedWidget objects from my WindowManager object, How can I do that?

推荐答案

是Qt方法来完成你的任务。

Event filters are the Qt way to accomplish your task.

使你的 WindowManager 类一个子类 QObject 并提供其方法。

Make your WindowManager class a subclass of QObject and provide an implementation for its eventFilter() method.

之后,每次创建一个 AdaptedWidget 使用将您的 WindowManager 实例安装为事件过滤器。

After that, every time you create an AdaptedWidget use installEventFilter() to install your WindowManager instance as an event filter on it.

class WindowManager : public QObject
{
public:
...
bool eventFilter(QObject* obj, QEvent* ev);

private:
    std::stack<window_ptr> m_windowsStack;
}

bool WindowManager::eventFilter(QObject* obj, QEvent* ev){
    AdaptedWidget* widget= qobject_cast<AdaptedWidget*>(obj);
    if(ev->type == /*type of event you are interested in*/){
        //you can compare widget against the stack of widgets you have

        //if you want to stop widget from receiving the event you can return true
    }
    return false;
}

当创建每个 AdaptedWidget 实例,安装 WindowManager 作为事件过滤器:

and when creating each AdaptedWidget instance, install the WindowManager as an event filter:

AdaptedWidget* widget= new AdaptedWidget;
widget->installEventFilter(/*your WindowManager instance*/);

这篇关于了解其他课程发生的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 17:57