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。

虚拟模块.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;
}

虚拟模块.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
}

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

4

1 回答 1

3

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

...
QGraphicsItem *mod = itemAt(event->scenePos());
...
于 2013-06-04T14:57:29.420 回答