1

基本上,每次我单击图形视图时,我都希望出现一个新的 QGraphicsEllipseItem。数量由用户决定。另外,我想最后用 pos() 查询所有这些以获取它们的所有位置。椭圆的数量事先不知道,它们的位置可以通过 ItemIsMovable 标志移动。任何人都知道我该怎么做?

我可以制作一个指向 graphicsitem 类的指针数组,但这可能会浪费内存并限制我可以制作的椭圆数。谢谢。

4

1 回答 1

2

您可以在场景中添加任意数量的项目(当然,只要有可用的内存空间):

myGraphicsScene->addEllipse(rect, pen, brush);

为了为每次点击添加项目,重新mousePressEvent实现QGraphicsView

void MyGraphicsView::mousePressEvent(QMouseEvent *e)
{
    int rx = 10; // radius of the ellipse
    int ry = 20;
    QRect rect(e->x() - rx, e->y() - ry, 2*rx, 2*ry);
    scene()->addEllipse(rect, pen, brush);

    // call the mousePressEvent of the super class:
    QGraphicsView::mousePressEvent(e);
}

您不必自己存储指针。当你想查询场景中所有物品的某条信息时,只需遍历场景提供的物品列表即可:

foreach(QGraphicsItem *item, myGraphicsScene->items())
    qDebug() << "Item geometry =" << item->boundingRect();

(或仅适用于该职位item->pos():)

如果要查询 的子类的一条信息QGraphicsItem,可以使用 Qt 的 QGraphicsItem 转换机制将该项目转换为您的类型,如果该项目不是请求的类型,则该机制返回一个空指针。检查指针不为空后,您可以访问自己的成员:

foreach(QGraphicsItem *item, myGraphicsScene->items())
{
    MyDerivedItem *derivedItem = qgraphicsitem_cast<MyDerivedItem*>(item);
    if(derivedItem) // check success of QGraphicsItem cast
        qDebug() << derivedItem->yourCustomMethod();
}
于 2012-05-23T22:38:21.653 回答