Constantin
Constantin

Reputation: 17768

Replacing QPen's - How Do I Delete

I am developing a GUI which will allow the user to modify ellipses using mouse/QSpinBox events on top of a background picture.

I want to set it up so that when a user clicks on an ellipse, the ellipse changes color and has been "selected."

I am using QGraphicsView/Scene with QGraphicsEllipseItem. Here in lies my problem, the setPen(QPen & const) call is a reference thus:

Anyways, I must be approaching this wrong, could any offer any suggestions?

P.S. - I would like to avoid making yet ANOTHER member variable. I am going to have many ellipses, each one should not have its own pen variable!


This code will cause a segfault:

void MyClass::SetupEllipses()
{
    QPen pen();
    pen.setColor(QColor(255,0,0));
    pen.setWidth(2);

    m_ellipse = new QGraphicsItemEllipse(); //This is a member variable of MyClass
    m_ellipse->setRect(some ssize here);
    m_ellipse->setPen(pen);

    m_graphicsview->scene()->addItem(m_ellipse); //m_graphicsview is also a member variable of MyClass and has had a scene added to it.
}

Upvotes: 1

Views: 186

Answers (1)

Frank Osterfeld
Frank Osterfeld

Reputation: 25165

If I allocate a pen on the stack and pass it in, I get a segfault.

That's the right way - if you get a segfault, that's certainly not due to the QPen. Post your code and debugger stack trace.

Each QGraphicsEllipseItem will store a (light-weight) copy of the QPen anyway, so creating QPen instances on the heap is nonsensical and error-prone. Do not worry about too many QPen instances. QPen uses implicit sharing, i.e. if you share the same unmodified pen, the copies are cheap.

Upvotes: 2

Related Questions