views:

15

answers:

1

Apologies if this is a bit of a vague question with no proper answer. Please move/close it if it's not in the right place.

I've written a few relatively trivial GUIs in WxWidgets and Qt, and I'm persistently unsure how to architecturally handle the following situations:

  • You catch a mouse event to do something to a graphical object in your GUI
  • What you do with the object depends on which modifier keys the user is holding down

At the start I usually do something like the following:

void MyClass::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    if (event->modifiers() & Qt::AltModifier) {
        // do something
    } else if (event->modifiers() & Qt::ControlModifier) {
        // do something else
    } else {
        // do yet another thing  
    }
}

// Repreat ad-nausium for other mouse click/move events...

(This is a general question, I could paste similar code for toolkits other than Qt.)

Eventually, with similar if/else/switch code in lots of mousePressEvent, mouseReleaseEvent handlers, this seems a bit unwieldy so I try and encapsulate some of the repetition by putting the object into different "modes" depending on which modifiers are down. Nonetheless, I still feel I'm missing some nice elegant solution. I've tried to look at the code of various open-source tools but I've not found anything tangible (erm, simple) enough to point me in a different direction.

Some tools (say, the GIMP) seem to have so many rich and varied tool- and modifier-dependent behaviours that I feel there's got to be a nice way of architecting this pattern. Any suggestions would be gratefully received.

A: 

IMHO, event handling in such a GUI toolkits decides what to do according to an event and an event handler you provide. What you need is a way to decide what to do according to an event, modifier and an event handler. So you can based on your events and modifier call special event processing object in all of your standard event handlers for events provided by the toolit. What you have to implement is that event processing object, which will according to an even and modifier call the right behaviour (event+modifier handler). This is what I would call Chain of responsibility design pattern.

Gabriel Ščerbák
@Gabriel: Thanks for your input, it's given me some ideas. As you suggest defining a chain-of-responsibility-type cascading set of handlers seems to be a good way of managing the various permutations here. I'll do some more reading-up and try and figure out a good way of implementing it in my imagined context.
Mikesname