【问题标题】:itemAt not returning custom qGraphicsItemitemAt 不返回自定义 qGraphicsItem
【发布时间】:2013-06-04 23:09:05
【问题描述】:

我有一个自定义的 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 事件是在场景中创建和处理的,所以我认为绝对坐标不是问题。 AFAIK QGraphicsItem 也使用场景坐标?

标签: c++ qt qgraphicsscene


【解决方案1】:

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

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

【讨论】:

  • 哈,应该注意到了,谢谢。编译器不接受省略转换参数,知道为什么吗?
  • 变换应该来自视图。所以你应该测试QGraphicsSceneMouseEvent::widget() 成员是否是QGraphicsView,如果是,则从中提取transform()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2019-05-14
  • 1970-01-01
相关资源
最近更新 更多