Following on from this question, I have a menu system as follows:
MainMenu > (Load Game button clicked) > LoadGameMenu
LoadGameMenu > (Back To Main Menu button clicked) > MainMenu
LoadGameMenu > (Load button clicked) > GameScreen
However, when I click on the Load button, the MainMenu is shown instead. Here’s my code:
ApplicationWindow::ApplicationWindow()
{
resize(800, 600);
stack = new QStackedWidget(this);
signalMapper = new QSignalMapper(this);
mainMenu = new MainMenu(this);
loadGameMenu = new LoadGameMenu(this);
gameScreen = new GameScreen(this);
stack->addWidget(mainMenu);
stack->addWidget(loadGameMenu);
stack->addWidget(gameScreen);
connect(mainMenu, SIGNAL(loadGameClicked()), signalMapper, SLOT(map()));
connect(loadGameMenu, SIGNAL(backToMainMenuClicked()), signalMapper, SLOT(map()));
connect(loadGameMenu, SIGNAL(loadClicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(loadGameMenu, 0);
signalMapper->setMapping(mainMenu, 1);
signalMapper->setMapping(gameScreen, 2);
connect(signalMapper, SIGNAL(mapped(int)), stack, SLOT(setCurrentIndex(int)));
setCentralWidget(stack);
}
I know I’m doing something wrong with the signal mapping, but I don’t know what it is.
Cheers.
1)
QSignalMappermaps aQObject* senderto a (int, string, QWidget* or QObject*). Since your “load” and “return to main menu” signals are being sent from the same sender object they will be mapped the same way. The solution is to connect theclickedsignal of the different buttons to the mapper directly (rather than through yourLoadGameMenuobject), so the sender is different.2) Since you’re using a
QStackedWidget, I would strongly consider using theQWidget*mapping ofQSignalMapper, and connect toQStackedWidget::setCurrentWidget. This will be easier to maintain if/when you add more menu screens, rather than trying to keep up with whichintindex is which widget. It also makes things more readable in your code, in my opinion.Edit: Looks like you’re not understanding the
setMappingfunction. I’d take a look at the docs for better a better idea. What you’re doing there is mapping the first argument (the sender) to a signal to be sent (the second argument). In your original code, you’re mappingLoadGameMenuto0. Any time a signal is sent to the mapper fromLoadGameMenu,0is sent to stackedWidget::setCurrentIndex` – which is why both buttons are returning you to the same place.