gpt4 book ai didi

c++ - QGraphicsScene 不响应合成事件

转载 作者:行者123 更新时间:2023-11-30 04:35:39 24 4
gpt4 key购买 nike

我有一个非常简单的 QGraphicsScene 派生类:

class SceneComponent : public QGraphicsScene
{
Q_OBJECT
public:
explicit SceneComponent(QObject* parent = 0);

protected:
void mousePressEvent(QGraphicsSceneMouseEvent*);
};

mousePressEvent(QGraphicsSceneMouseEvent*)定义为:

void SceneComponent::mousePressEvent(QGraphicsSceneMouseEvent* event) {
Q_UNUSED(event);
std::cout<<"[Processing] MouseEvent"<<std::endl;
}

要显示这个 QGraphicsView,这很简单:

QGraphicsView view(sceneComp);
view.show();

现在,当我单击显示的窗口(对于 QGraphicsView)时,我得到以下输出:

[Processing] MouseEvent
[Processing] MouseEvent

但是,当我使用以下方式发送合成事件时:

QMouseEvent* mevent = new QMouseEvent(
QMouseEvent::MouseButtonPress, QPoint(50, 50),
Qt::LeftButton, Qt::NoButton, Qt::NoModifier
);
QApplication::sendEvent(&view, mevent);

我完全没有输出。这是为什么?

相关说明,在 QGraphicsScene 上安装 eventFilter 根本不会产生任何结果。这可能(在我看来)是因为 QGraphicsScene 需要 QGraphicsSceneMouseEvent 而不是 QMouseEvent。这支持了两个问题:

  1. 为什么 QGraphicsScene 不接受标准 QEvent 而只接受 QGraphicsSceneEvent?
  2. 为什么任何 QGraphicsSceneEvent 派生类都不可实例化?
  3. 为什么我可以使用 sceneEvent 方法将事件发送到 QGraphicsScene,但我需要指定一个特定的 QGraphicsItem 来发送事件?

最佳答案

来自 QGraphicsSceneEvent 的文档:

When a QGraphicsView receives Qt mouse, keyboard, and drag and drop events (QMouseEvent, QKeyEvent, QDragEvent, etc.), it translates them into instances of QGraphicsSceneEvent subclasses and forwards them to the QGraphicsScene it displays. The scene then forwards the events to the relevant items.

For example, when a QGraphicsView receives a QMouseEvent of type MousePress as a response to a user click, the view sends a QGraphicsSceneMouseEvent of type GraphicsSceneMousePress to the underlying QGraphicsScene through its mousePressEvent() function. The default QGraphicsScene::mousePressEvent() implementation determines which item was clicked and forwards the event to QGraphicsItem::mousePressEvent().

  1. QGraphicsView使用视口(viewport)小部件来显示场景的内容并接收用户事件。尝试将您的事件发送到 QGraphicsView::viewport()小部件 - 它应该可以工作。
  2. 按照设计 - 请参阅引文,这些事件可能不打算手动发送。 QMouseEvent与 body Action 相关 - 例如。鼠标点击,同时 QGraphicsSceneMouseEvent是抽象的东西...
  3. 问题不清楚,但该引用可能也有帮助。您具体指的是哪个事件?您还应该记住 QGraphicsSceneQObject级别事件,与 QApplication::sendEvent() 一起发送, 和 QGraphicsItemQGraphicsScene::sendEvent() 一起发送的事件.这两种工作在不同的层面,有不同的目的。有关详细信息,请参阅文档。

关于c++ - QGraphicsScene 不响应合成事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5080181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com