c++ - QGraphicsPixmapItem mouseMoveEvent 不抓取时

标签 c++ qt user-interface graphics mouseevent

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

正在关注 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 配置为“抓取器”的情况下触发 mouseMoveEvent 处理程序。如果鼠标第一次移动到项目上时自动配置为抓取器,这也是可以接受的。

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

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

我想这不相关。

最佳答案

解决方案是重新实现或过滤项目的 hoverMoveEvent , 作为 mouseMoveEvent仅在接收到鼠标按下时触发:

If you do receive this event, you can be certain that this item also received a mouse press event, and that this item is the current mouse grabber.

关于c++ - QGraphicsPixmapItem mouseMoveEvent 不抓取时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12090005/

相关文章:

python - 设置自定义标题栏小部件会更改 Windows 上的窗口标志

java - 如何在带注释的 UIThreadTest 方法中说 waitForIdleSync()

c++ - 结构中 union 的 const 成员的问题

c++ - Qt Directx 渲染

c++ - Qt:包含 .pri 以使用库 - 不正确的包含

c++ - 如何在对象创建时从 QML 调用任意 C++ 函数?

java - GUI 一次显示阵列的每个图像

android - 如何动态创建一个按钮并为其分配一个在 styles.xml 中定义的样式?

c++ - is_invocable 具有任意函数参数类型

c++ - 这会导致对象切片吗?