View Full Version : Setting a QAbstractGraphicsShapeItem's pen fields

13th August 2010, 07:26
I've created a rectangle (QGraphicsRectItem) for use in a QGraphicsScene. I want to change the colour of the shape (say, a blue pen) while leaving all other fields in their default state. I've been able to do this by creating a new QPen and setting it to the one use by the rectangle, like so:

myScene = new QGraphicsScene(this);
myScene->setSceneRect(0, 0, 500.0, 500.0 ); //Set the scene's outline

QGraphicsRectItem *myRect = new QGraphicsRectItem;

QPen *myPen = new QPen(Qt::blue); //Create a new, blue pen
myRect->setPen(*myPen); //Set the rectangle's pen

myRect->setRect(100, 100, 100, 100); //Set rectangle size and position
graphScene->addItem(pixel); //Add the rectangle to the scene

Probably a really basic question, but what is wrong with trying to set the colour with the following line?


Do I not have access to the "setColor" function in the rectangle's pen?
Am I accessing it in an incorrect manner?
If I place that line in the above code instead of lines 7 & 8, it throws no errors/warnings, but it does nothing (the colour of the rectangle doesn't change).

If I only want to change the pen's colour, it seems weird to me (someone inexperienced with OO programming) to be required to create a new pen and assign it to the rectangle rather than just changing the color in the existing default pen created when the rectangle is created, which is why I thought I'd ask and see if there is an easier way.

13th August 2010, 20:03

The QPen object returned is const.

14th August 2010, 14:14
Ah OK. Somehow I missed that.
So does that mean that basically the only way to set, say, the pen's colour to red is with the following statement?


16th August 2010, 18:51
Ah OK. Somehow I missed that.

Indeed. I would say that *that* is the bigger problem, i.e., Qt apparently (?) didn't tell you that you were attempting to change a const variable.

17th August 2010, 03:28
Qt apparently (?) didn't tell you that you were attempting to change a const variable.
Well there's no warning during compilation, or error while running, but the pen colour doesn't change, so I'm not sure exactly what's going on.