Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 动态添加QGraphicsSellipseItems_C++_Qt_Qgraphicsitem - Fatal编程技术网

C++ 动态添加QGraphicsSellipseItems

C++ 动态添加QGraphicsSellipseItems,c++,qt,qgraphicsitem,C++,Qt,Qgraphicsitem,基本上,每次单击graphicsview时,我都希望出现一个新的QGraphicsSellipseitem。号码由用户决定。另外,我想在最后用pos()查询所有的位置。椭圆的数量在手之前是未知的,它们的位置可以通过ItemIsMovable标志移动。有人知道我怎么做吗 我可以创建一个指向graphicsitem类的指针数组,但这可能会浪费内存并限制我可以创建的椭圆的数量。谢谢。您可以在场景中添加任意数量的项目(当然,只要有可用的内存空间): 要为每次单击添加项目,请重新实现QGraphicsVi

基本上,每次单击graphicsview时,我都希望出现一个新的QGraphicsSellipseitem。号码由用户决定。另外,我想在最后用pos()查询所有的位置。椭圆的数量在手之前是未知的,它们的位置可以通过ItemIsMovable标志移动。有人知道我怎么做吗


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

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

要为每次单击添加项目,请重新实现
QGraphicsView
mousePressEvent

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();

莱姆斯,再次谢谢你。有没有一种方法可以将foreach用于QGraphicsItem的子类,然后请求它提供我添加到类中的成员?如:foreach(Deriveditem*item,MyGraphicseCne->items())qDebug()当然可以;)请参阅我的最新答案。我希望这是你要求的。务必记住使用安全qobject_cast,并在使用前检查结果。这扩展到了QObject的每一个类型。最后一个示例不会编译<代码>qobject_cast接受qobject*,但QGraphicsItem不从qobject继承。您需要
qgraphicsitem\u cast
。请再次感谢您的回复。我不能让它完全正常工作。所讨论的类实际上是从QGraphicsSellipseitem派生的。我试图强制转换它,但编译器抱怨“调用'qobject_cast(QGraphicsItem*&')没有匹配的函数。”我尝试用QGraphicsItem_cast替换qobject_cast,但编译器说graphicsitem类没有我试图访问的member.Oops。执行不正确。以上代码适用于qgraphicsitem_cast替换。再次感谢你,莱姆斯。
foreach(QGraphicsItem *item, myGraphicsScene->items())
    qDebug() << "Item geometry =" << item->boundingRect();
foreach(QGraphicsItem *item, myGraphicsScene->items())
{
    MyDerivedItem *derivedItem = qgraphicsitem_cast<MyDerivedItem*>(item);
    if(derivedItem) // check success of QGraphicsItem cast
        qDebug() << derivedItem->yourCustomMethod();
}