PDA

View Full Version : Suggestion on how to use SIGNAL & SLOT to connect 2 QGraphicObjects



SlaynX
28th May 2011, 14:49
Hi all,

There is two GraphicObjects. Both have mousepressevent and also needed to be seen in a QGraphicsScene. The first GraphicObjects(let say A), when user clicks on it the second GraphicObjects(let say B) will be painted on the QGraphicScene while A still remain in the scene. But when user clicks on B the object A will be deleted together with B after being clicked. I use SIGNAL & SLOT to implement this which can only work for 1 pair. It became chaotic when there is plenty of object A in the scene. Please help me. I write down a pseudo code below.



class A
{
paint()//paints the object
mousePressEvent
{
emit drawBtn//emit signal
}
}

class B
{
mousePressEvent
{
emit DestroyA
emit DestroySelf
}
}

class Widget
{
Widget()
{
scene = new QGraphicsScene
view = new QGraphicsView
createA();//this one only work once.

}

void createA()
{
//create classA and add to the scene
connect(A, SIGNAL(drawBtn()),this,SLOT(drawTheBtn())
}
void drawTheBtn()
{
//create classB and add to the scene
connect(B, SIGNAL(destroyA()),A,SLOT(deleteLater())
connect(B, SIGNAL(destroySelf(),B,SLOT(deleteLater())
}

}

Lykurg
28th May 2011, 14:59
You can use the parent-child relation. If the parent of a QObject gets deleted, all children also get deleted.

SlaynX
28th May 2011, 17:02
Yeah already attempted that method however that doesn't solve the goal. The goal is classB only appear into the scene when classA receives a click from the user.

The goal is:
A(appear in the scene)--->user clicks on A---->B appear(appear on the scene)
---->user clicks on B-----A & B destroy.

Like I said previously I implemented with a different method and it works however only for one pair. Both also needed to be in the QGraphicsScene.

The problem having parent-child relationship i can't seem to add both item in the scene(scene.addItem) but only in the constructor of class A. Please help me. Thanks.

joyer83
28th May 2011, 20:17
So the problem is this connect:

connect(B, SIGNAL(destroyA()),A,SLOT(deleteLater())You have n-number of As to which you would need to connect the B's signal?
How about if you create an another class which knows all the As and it can delete them when necessary?
Something like this:


class Deleter {
void addA( A *a ) {
aList << a;
}
void deleteAs() {
// loop through aList, delete each A-object and then clear the list itself
}
QList<A*> aList;
}
When you create an A object you pass it to addA() and when B is clicked you call deleteAs().