了解其他班级发生的事件

时间:2016-12-16 15:59:56

标签: c++ qt events qwidget qevent

我有两个班级:

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个对象中发生的事件的信息,我该怎么做?

2 个答案:

答案 0 :(得分:1)

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

WindowManager类设为QObject的子类,并为其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*/);

答案 1 :(得分:1)

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

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

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