0

我需要制作一个 GUI 按钮,告诉它的父级(或父级的父级,甚至是父级的父级的父级......)QStackedLayout应该显示不同的小部件。我创建了一个自定义 QEvent:

class SwitchScreenEventWidget : public QEvent {
public:
  SwitchScreenEventWidget(QWidget* w) : SwitchScreenEvent(), widget(w) {
    if(widget==nullptr)
      throw "SwitchScreenEventWidget received null widget.";
  }
  virtual QWidget* getWidget() const {;return widget;}
private:
  QWidget* const widget;
};

我这样调用它:

// Through debugger I checked that this is getting called properly
void GraphButton::buttonClicked()
{
  if(qApp!=nullptr && parent()!=nullptr)
    qApp->notify(parent(), new SwitchScreenEventWidget(getGraph()));
}

并像这样处理它:

bool ViewStack::eventFilter(QEvent* e)
{
    if(e->type()>=QEvent::User) {
      if(SwitchScreenEvent* event = dynamic_cast<SwitchScreenEvent*>(e)) {
        // Show the given widget
      }
      return true;
    }
    return false;
}

我使用eventFilter它然后注册到主应用程序小部件。但是该事件没有被捕获。在某处我读到一些QEvents 根本不会在层次结构中冒泡。

那么所有事件都会冒泡吗?如果不是,哪些会,哪些不会,为什么?以及如何正确地使我的活动冒泡?

4

1 回答 1

0

我认为对你来说最好的方法是子类化QApplication,覆盖notify方法并自己做你的“气泡事件”。我很确定鼠标和键盘事件会通过这种方法“冒泡”,而其他事件不会。

bool QCoreApplication::notify(QObject * 接收者,QEvent * 事件)

向接收者发送事件:receiver->event(event)。返回从接收者的事件处理程序返回的值。请注意,对于发送到任何线程中的任何对象的所有事件,都会调用此函数。

对于某些类型的事件(例如鼠标和按键事件),如果接收者对该事件不感兴趣(即,它返回假),则该事件将被传播到接收者的父对象等等直到顶级对象。

所以你可以通过你的认识来改变这种行为。

还有关于你的代码示例。我认为这张支票

if( qApp!=nullptr )

没用,因为你总是会有 qApp 的实例。

于 2016-01-18T15:36:43.583 回答