Qt GraphicsEllipseItem numbering

239 views Asked by At

So I'm building this app in which I click on the graphicsView and a ellipse appears at the exact location where I clicked. All good and nice, now I want to number these ellipses. I want to set a text inside the ellipse. Like, when I click the first time on the graphicsView a ellipse shows up and inside it's written "1", then i click somewhere else again and another ellipse shows up, this time with the text "2" and so on...

2

There are 2 answers

2
Vlad Potra On

void Widget::mousePressEvent(QMouseEvent *mouseEvent)
{
    QPointF p = mouseEvent->localPos();
    if (mouseEvent->button() == Qt::LeftButton &&
        p.x() >= 20 && p.x() <= 780 && p.y() >= 20 && p.y() <= 780)
    {
        int l = 40;
        count++;
        elipse[count] = scene->addEllipse(p.x()-l/2-14, p.y()-l/2-14, l, l, QPen(Qt::black));
        elipse[count]->setFlags(QGraphicsEllipseItem::ItemIsMovable)    
    }
}

So this is the function. I want to add text, and DO NOT forget, the item is MOVABLE, so if the item moves, the text must also move.

EDIT! I Figured it out!

void Widget::mousePressEvent(QMouseEvent *mouseEvent)
{
    QPointF p = mouseEvent->localPos();
    if (mouseEvent->button() == Qt::LeftButton &&
        p.x() >= 20 && p.x() <= 780 && p.y() >= 20 && p.y() <= 780)
    {
        int l = 40;
        count++;
        elipse[count] = scene->addEllipse(p.x()-l/2-14, p.y()-l/2-14, l, l, QPen(Qt::black));
        elipse[count]->setFlags(QGraphicsEllipseItem::ItemIsMovable);

        enumbering[count] = scene->addSimpleText(QString::number(count));
        enumbering[count]->setPos(p.x()-l/2+3, p.y()-l/2-1);

        enumbering[count]->setParentItem(elipse[count]);
    }
}

0
Félix Cantournet On

Create a class to draw the ellipse,deriving from QGraphicsEllipseItem (maybe this is already done) Insert the ellipse into the scene with scene->addItem() The move the ellipse with setpos()

In that class create a static member static int ellipse_count and initialise it to 0. Increase that counter everytime you create an ellipse, and decrease it everytimeyou destroy one (put the code increasing and decreasing the counter in the constructor and destructor)

You can add a member to your ellipse class as a QGraphicsTextItem and create the object and place it inside the ellipse constructor. This way you can place the Text itemin relative coordinate inside the ellipse referential and it will move with the ellipse.