【问题标题】:QGraphicsPixmapItem mouseMoveEvent when not grabbing不抓取时的QGraphicsPixmapItem mouseMoveEvent
【发布时间】:2012-08-23 10:53:16
【问题描述】:

我正在开发一个使用 Qt 4.8 作为 GUI 框架的 C++ 应用程序: 子类 QGraphicsView 呈现包含一个或多个子类 QGraphicsPixMapItem(s) 的子类 QGraphicsScene,我需要在其中知道鼠标光标的相对像素位置。

跟随How to show pixel position and color from a QGraphicsPixmapItem我子类QGraphicsPixmapItem

class MyGraphicsPixmapItem : public QObject, public QGraphicsPixmapItem
{
    Q_OBJECT
public:
    explicit MyGraphicsPixmapItem(QGraphicsItem *parent = 0);
signals:
public slots:
    void mouseMoveEvent(QGraphicsSceneMouseEvent * event);
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
};

并实现构造函数和处理程序:

MyGraphicsPixmapItem::MyGraphicsPixmapItem(QGraphicsItem *parent) : QGraphicsPixmapItem(parent)
{
    qDebug() << "constructor mygraphicspixmapitem";
    setCacheMode(NoCache);
    setAcceptHoverEvents(true);
    setFlag(QGraphicsItem::ItemIsSelectable,true);
}

void MyGraphicsPixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
    QPointF mousePosition = event->pos(); 
    qDebug() << "mouseMoveEvent";
    qDebug() << mousePosition;
    QGraphicsPixmapItem::mouseMoveEvent(event);
}

我还使用各自的 mouseMoveEvent 处理程序将 QGraphicsView 和 QGraphicsScene 子类化,这些处理程序可以成功地进一步向下传递事件:

void MyGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    qDebug() << "QGraphicsScene: mouseMoveEvent";
    QGraphicsScene::mouseMoveEvent(event);
}

然而,虽然 MyGraphicsView 配置了 ...

setMouseTracking(true);
setInteractive(true);

... MyGraphicsPixmapItem 仅在被单击或设置为抓取器后才执行 mouseMoveEvent 处理程序:

void MyGraphicsPixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    qDebug() << QString("item clicked at: %1, %2").arg( event->pos().x()).arg( event->pos().y()  );
    event->accept();
    grabMouse();
}

我想知道我是否犯了错误或上述答案中给出的解决方案有缺陷或不完整。此外,我想知道是否可以在没有将 QGraphicsPixmapItem 配置为“grabber”的情况下触发 mouseMoveEvent 处理程序。如果在鼠标第一次移动到项目上时自动发生作为抓取器的配置也是可以接受的。

这是一个thread,其中一个非常相似的问题似乎与该项目的引用有关,但由于我将项目添加到这样的场景中:

thepixMapItem = new MyGraphicsPixmapItem();
scene->addItem(thepixMapItem);

我想这不相关。

【问题讨论】:

  • 另外,一旦item是一个grabber,如果鼠标在元素之外,它甚至会触发mouseMoveEvent。这不是我的目的。
  • 如果你覆盖 QGraphicsItem::sceneEvent 你会看到事件吗? (即在此处理程序中查看具有适当类型字段的事件)
  • @Pete 是的,布尔 MyGraphicsPixmapItem::sceneEvent(QEvent *event) { qDebug()
  • 也许我应该只使用 hoverMoveEvent。这几乎可以满足我的要求!

标签: c++ qt user-interface graphics mouseevent


【解决方案1】:

解决方法是重新实现或过滤item的hoverMoveEvent,因为mouseMoveEvent只有在收到鼠标按下时才会触发:

如果您确实收到了此事件,则可以确定 此项目也 收到鼠标按下事件,并且该项目是当前鼠标 抓取器。

【讨论】:

    猜你喜欢
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2021-01-26
    • 1970-01-01
    • 2011-10-16
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多