itemAt不返回自定义qGraphicsItem

时间:2013-06-04 13:58:22

标签: c++ qt qgraphicsscene

我有一个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
}

我的实施有问题吗?有什么我想念的吗?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您正在项目坐标而不是场景坐标中查询场景。使用:

...
QGraphicsItem *mod = itemAt(event->scenePos());
...