tags:

views:

470

answers:

2

What's the best way to go about creating a play/pause button in Qt? Should I create one action and change it's icon when clicked, or should I create two actions and then somehow hide one when clicked? How do I use one shortcut key to activate both actions? (Pause when playing, or play when paused).

+3  A: 

Keep it simple. Use the same button, but when handling the clicking, change the icon and choose the handling logic (play or pause) based on current status (pause when playing or playing when paused).

In order to keep the code clear, implement two separate methods, one for play and one for pause and call them from the slot of the button, depeding on the status.

Cătălin Pitiș
I would actually have to change the icon, the text, the status tip, the slot, and instead of calling the play() or pause() slots directly, I'd have to call a function in the same class to update the button, and then propagate the action... makes more sense to have two actions which you can switch so you don't have to manage changing all those properties.
Mark
To me, it looks simpler to have a conditional call in a single slot method, than disconnecting and reconnecting a slot... But maybe it is a matter of prefference :)
Cătălin Pitiș
Well you wouldn't have to disc/reconnect if you had two separate actions, no? I didn't realize you meant one slot for both actions though... that *might* work better. Have to think about this ab it more.
Mark
A: 

I think something like this is easiest/most appropriate:

playAct = new QAction(QIcon(":/icons/elementary/media-playback-start.png"), tr("&Run"), controlActGroup);
playAct->setShortcut(Qt::Key_Space);
playAct->setCheckable(true);
playAct->setStatusTip(tr("Run physics"));
connect(playAct, SIGNAL(triggered()), editorView, SLOT(runPhysics()));

pauseAct = new QAction(QIcon(":/icons/elementary/media-playback-pause.png"), tr("&Pause"), controlActGroup);
pauseAct->setShortcut(Qt::Key_Space);
pauseAct->setCheckable(true);
pauseAct->setStatusTip(tr("Pause physics"));
connect(pauseAct, SIGNAL(triggered()), editorView, SLOT(pausePhysics()));

connect(playAct, SIGNAL(toggled(bool)), pauseAct, SLOT(setVisible(bool)));
connect(pauseAct, SIGNAL(toggled(bool)), playAct, SLOT(setVisible(bool)));
pauseAct->setChecked(true);
pauseAct->setVisible(false);

The only thing I don't like is that the actions are controlling the OTHER button's visibility status. Since there is no setInvisible function I couldn't hook it up so that they could hide themselves when clicked.

That, and it seems to create a visual gap where the hidden button was (at least on Ubuntu).

Mark