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).
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.
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).
You can add both play and pause actions to the toolbar and to the menu of the main window and make the pause action invisible. When you need to switch this actions you will only have to change visibility of the actions and it takes affect on menu and on toolbar simultaneously. It's convenient, code is compact.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With