从其他 class 那里了解发生的事件

Learn about occurred events from other class

我有两个类:

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);
}

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

Event filters 是完成任务的 Qt 方式。

使您的 WindowManager class 成为 QObject 的子 class 并为其 eventFilter() 方法提供一个实现。

之后,每次创建 AdaptedWidget 时,使用 installEventFilter() 安装 WindowManager 实例作为其上的事件过滤器。

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 作为事件过滤器:

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

AdaptedWidget class 应该有一个指示鼠标按下的信号,例如

class AdaptedWidget : ... {
  Q_OBJECT
  ...
public:
  Q_SIGNAL void mousePress(const QPoint &);
};

bool AdaptedWidget::event(QEvent *event)
{
    if (event->type() == QEvent::NonClientAreaMouseButtonPress ||
        event->type() == QEvent::MouseButtonPress)
    {
        auto ev = static_cast<QMouseEvent*>(event);
        emit mousePress(ev->pos());
        qDebug() << "mainwindow press";
    }
    return QWidget::event(event);
}

另一种方法是使用事件过滤器,但这会不必要地将两个 class 紧密耦合。