This is my first Qt app and also some of my first non-trivial C++ code. The application displays a menu offering two options. Clicking either option takes you to a sub-page with some text and a back button, taking you back to the menu.
Feedback I'm especially interested in:
- Am I doing anything weird, culturally, either in C++ culture or Qt culture?
- Am I using the wrong tool for the job at any point, for instance in my use of QStackedLayout?
- Is the design robust? For instance, adding buttons to the menu happens separately to adding pages to the StackedLayout. Should I create a MultiPageEnvironment class or something to handle this automatically?
- Any major C++ or Qt no-nos?
main.cpp
#include <QApplication>
#include "MainWindow.h"
int main(int argc, char **argv)
{
QApplication *app = new QApplication(argc, argv);
MainWindow *mw = new MainWindow();
mw -> show();
return app -> exec();
}
MainWindow.cpp
#include <stdio.h>
#include <QWidget>
#include <QPushButton>
#include <QStackedLayout>
#include "MainWindow.h"
#include "MenuPage.h"
#include "SubPage.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
setWindowTitle("Application");
layout = new QStackedLayout();
MenuPage *menuPage = new MenuPage(this);
SubPage *page1 = new SubPage("This is page one.", this);
SubPage *page2 = new SubPage("This is page two.", this);
layout -> addWidget(menuPage);
layout -> addWidget(page1);
layout -> addWidget(page2);
layout -> setCurrentIndex(0);
this -> setLayout(layout);
menuPage -> addButton();
menuPage -> addButton();
}
void MainWindow::setPage(int index)
{
layout -> setCurrentIndex(index);
}
void MainWindow::goToMenu()
{
layout -> setCurrentIndex(0);
}
MenuPage.cpp
#include <stdio.h>
#include <QWidget>
#include <QPushButton>
#include <QSignalMapper>
#include "MenuPage.h"
MenuPage::MenuPage(MainWindow *parent) : QWidget(parent)
{
signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)), parent, SLOT(setPage(int)));
layout = new QVBoxLayout();
setLayout(layout);
nButtons = 0;
}
void MenuPage::addButton()
{
nButtons += 1;
QString label = (new QString("Page %1")) -> arg(nButtons);
QPushButton *button = new QPushButton(label, this);
layout -> addWidget(button);
signalMapper -> setMapping(button, nButtons);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
}
SubPage.cpp
#include <stdio.h>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include "SubPage.h"
#include "MainWindow.h"
SubPage::SubPage(const char messageString[], MainWindow *parent) : QWidget(parent)
{
message = new QLabel(messageString, this);
backButton = new QPushButton("Back", this);
QVBoxLayout *layout = new QVBoxLayout();
layout -> addWidget(message);
layout -> addWidget(backButton);
setLayout(layout);
connect(backButton, SIGNAL(clicked()), parent, SLOT(goToMenu()));
}
stdio.h
or why is it included? \$\endgroup\$MainWindow.h
,MenuPage.h
andSubPage.h
. Without those, the code won't compile. \$\endgroup\$