itemAt不返回自定义qGraphicsItem。

4

我有一个自定义的qGraphicsScene实现和一个自定义的qGraphicsItem,我点击它,但itemAt函数从来没有返回值,尽管我相当确定我点击了该项。

void VScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if ((vMouseClick) && (event->pos() == vLastPoint)) {
        QGraphicsItem *mod = itemAt(event->pos(), QTransform());
        if (mod) { // Never returns true
            // ...
        }
    }
}

为了更清晰明了,以下代码中添加了模块:

void VScene::addModule(QString modName, QPointF dropPos)
{
    VModule *module = new VModule();
    addItem(module);
    // the QPointF value comes from an event in mainWindow, the coordinate is mapped to my scene.
    module->setPos(dropPos);
}

...这里是我写的自定义qGraphicsItem。

VModule.h:

class VModule : public QObject, public QGraphicsItem
{
    public:
        explicit VModule();
        QRectF boundingRect() const;
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

    private:
        qreal w;
        qreal h;
        int xAddr;
        int yAddr;
        QPolygonF baseShape;
}

VModule.cpp:

VModule::VModule()
{
    w = 80;
    h = 80;
    xAddr = w / 2;
    yAddr = h / 2;

    // Use the numbers to create a number of polygons
    QVector<QPointF> basePoints = { QPointF(0.0, 0.0),
                                    QPointF(xAddr, yAddr),
                                    QPointF(0.0, yAddr * 2),
                                    QPointF(-xAddr, yAddr) };
    baseShape = QPolygonF(basePoints);
}

QRectF VModule::boundingRect() const
{
    return QRectF(-xAddr, 0, w, h);
}

void VModule::paint(QPainter *painter, const QStypeOptionGraphicsItem *option, QWidget *widget)
{
    // brushes and so on are set
    // ...

    painter->drawPolygon(baseShape, qt::OddEvenFill);

    // there are other polygons are drawn in the same way as above
}

我的实现有什么问题吗?我是否遗漏了什么?感谢您提前的帮助。

可能是一些坐标转换问题(例如,您获得了绝对屏幕坐标,但场景期望其自己的坐标),但我不确定。 - Lol4t0
@Lol4t0 事件是在场景中创建和处理的,所以我认为绝对坐标不是问题。据我所知,QGraphicsItem 也使用场景坐标? - c0nn
1个回答

3
您正在使用物品坐标而非场景坐标查询场景。请使用以下代码:
...
QGraphicsItem *mod = itemAt(event->scenePos());
...

嗨,本应注意到这一点,谢谢。编译器不会接受省略变换参数,有什么想法为什么会这样? - c0nn
2
变换应该来自视图。因此,您应该测试QGraphicsSceneMouseEvent::widget()成员是否为QGraphicsView,如果是,则从中提取transform() - cmannett85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接