基本上,每次点击图形视图时,我都希望出现一个新的QGraphicsEllipseItem。该号码取决于用户。另外,我想用pos()查询所有这些,以获得他们所有的位置。省略号的数量在手前是未知的,它们的位置可以通过ItemIsMovable标志移动。任何人都知道我怎么能这样做?
我可以创建一个指向graphicsitem类的指针数组,但这可能会浪费内存并限制我可以制作的省略号。感谢。
答案 0 :(得分:2)
您可以根据需要为场景添加任意数量的项目(当然,只要有可用的内存空间):
myGraphicsScene->addEllipse(rect, pen, brush);
要为每次点击添加项目,请重新实施mousePressEvent
的{{1}}:
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()
子类的一条信息,可以使用Qt的QGraphicsItem转换机制将项目转换为您的类型,如果该项目不是请求的,则返回空指针类型。检查指针不为空后,您可以访问自己的成员:
QGraphicsItem