PDA

View Full Version : Hiding QGraphicsRectItems



ddze
28th January 2011, 23:44
I am trying to use hide() show() or setVisible(false) function with QGraphicsRectItem objects. I can display them on the scene but no way I can do anything to hide them from screen. I have initialised them in the following code :



rectItems = new QVector<QGraphicsRectItem *>();

for (int raw=0;raw<this->qElementsHeight;raw++){
for(int column=0;column<this->qElementsWidth;column++){
QRectF rectF( raw*48, column*48, 48, 48 );
QGraphicsRectItem *rect = new QGraphicsRectItem(rectF);
rect->setPen(pen);
rectItems->push_back(rect);
rectItems->last()->setVisible(false);
this->addRect(rectItems->last()->rect(),pen);
}
}

then tried to use hide() in a slot function:


for (int c=0;c<rectItems->count();c++){
QGraphicsRectItem *temp =rectItems->at(c);
if(bGrid) {
//temp->setVisible(true);
//temp->show();
rectItems[0].at(c)->setVisible(true);
}
else {
//temp->setVisible(false);
//temp->hide();
rectItems[0].at(c)->setVisible(false);
}
}

none of it hides the rectangles in the scene. Is there a way of hiding them ?

wysota
29th January 2011, 00:11
Your code shouldn't even compile. Please check it out.
It should probably be:

rectItems[i]->hide();

ddze
29th January 2011, 00:28
Well it compiles perfectly.

QVector<QGraphicsRectItem *> *rectItems;

Lykurg
29th January 2011, 06:38
First please reconsider what wysota has told you:
rectItems[0].at(c)won't work like you expect it, second your pointer are all meaningless. Why? Because addRect() creates new items which are added to the scene. You have to store the pointers addRect() returns or simply use addItem().

ddze
29th January 2011, 10:01
Why should I consider wysota ?

This is corrected code with little bit of mix pointer formats for him and you revising your comments.

Correct Code:

void QSystem::drawGrid() {
bGrid=!bGrid;
for (int c=0;c<rectItems->count();c++){
if(bGrid) {rectItems->at(c)->show();}
else {rectItems[0].at(c)->hide();}
}
}

Correct addRect:

QGraphicsRectItem *rect=this->addRect(rectF,pen);

My mistake : I was in rush and did not read the QT Class QGraphicsScene addRect properly.
QGraphicsRectItem * QGraphicsScene::addRect ( const QRectF & rect, const QPen & pen = QPen(), const QBrush & brush = QBrush() )
I have mistakenly used QGraphicsRectItem instead of QRectF.

Wrong:

this->addRect(rectItems->last()->rect(),pen);