PDA

View Full Version : When should I use signal/slot mechanism



Bryku
10th February 2010, 17:42
Hi.
I love signals/slots mechanism, and im afraid that i can overuse it(or maybe i don't understand it : P ) :D
For example, I have 2 objects. First one inherits from QPixmapGraphicsItem , second one is QGraphicsScene. When i click on a QPixmap... object , a want to display it in QGraphicsScene. And i have 2 possible solutions. Use signal/slots mechanism, or simply call a method.

Here is my reimplementation of mousePressEvent




connect(this,SIGNAL(projectNewPixmapInViewWidget(c onst QPixmap &)),mediator->getPToCardVDW(),SLOT(setNewPixmap(const QPixmap &))); //necessary or not ?

void cCardBase::mousePressEvent(QGraphicsSceneMouseEven t *event)
{
switch(event->button())
{
case Qt::LeftButton :
//Should I emit signal here ?
//emit projectNewPixmapInViewWidget(this->pixmap());
//or simply
//mediator->getPToCardVDW()->setNewPixmap(this->pixmap());
break;
..............


And a slot in QGraphicsScene based object



card = new QGraphicsPixmapItem(QPixmap(tr("./graphics/misc/empty.jpg")));

void cCardViewDockWidget::setNewPixmap(const QPixmap &pixmap)
{
card->setPixmap(pixmap);
}//setNewPixmap()


And maybe some pictures :D

http://i48.tinypic.com/15388r4.jpg


http://i49.tinypic.com/2u47f6b.jpg



So, in that case should I emit a signal or call a method ^^'

Regards

squidge
10th February 2010, 19:14
I think of signal/slots as being able to reuse existing code more easily. It then doesn't depend on other classes (and doesn't care about them). Other classes can connect to it's signals and decide what methods they want to call as a result of those signals being raised.

If your class containing the signal already has a relationship with another class, and that class is the only one interested in that signal, then I see no reason to actually use signals/slots in that case. Call the method directly. It'll be faster too.

franz
10th February 2010, 21:31
Even so, the relation ship might only go one way (as with model/view), so signals/slots may still be the way to go.

In case of your example, I agree with fatjuicymole.

Bryku
10th February 2010, 22:24
thnx guys : )