Time for action – Public interface of the dialog
The next thing to do is to allow to store and read player names from outside the dialog—since the ui component is private, there is no access to it from outside the class code. This is a common situation and one that Qt is also compliant with. Each data field in almost every Qt class is private and may contain accessors (a getter and optionally a setter), which are public methods that allow us to read and store values for data fields. Our dialog has two such fields—the names for the two players.
Names of setter methods in Qt are usually started with set, followed by the name of the property with the first letter converted to uppercase. In our situation, the two setters will be called setPlayer1Name and setPlayer2Name, and they will both accept QString and return void. Declare them in the class header, as shown in the following code snippet:
void setPlayer1Name(const QString &p1name); void setPlayer2Name(const QString &p2name);
Implement their bodies in the .cpp file:
void ConfigurationDialog::setPlayer1Name(const QString &p1name) { ui->player1Name->setText(p1name); } void ConfigurationDialog::setPlayer2Name(const QString &p2name) { ui->player2Name->setText(p2name); }
Getter methods in Qt are usually called the same as the property that they are related to—player1Name and player2Name. Put the following code in the header file:
QString player1Name() const; QString player2Name() const;
Put the following code in the implementation file:
QString ConfigurationDialog::player1Name() const { return ui->player1Name->text(); } QString ConfigurationDialog::player2Name() const { return ui->player2Name->text(); }
Our dialog is now ready. Let's use it in the MainWindow::startNewGame function to request player names before starting the game:
ConfigurationDialog dialog(this); if(dialog.exec() == QDialog::Rejected) { return; // do nothing if dialog rejected } ui->player1Name->setText(dialog.player1Name()); ui->player2Name->setText(dialog.player2Name()); ui->gameBoard->initNewGame();
In this slot, we create the settings dialog and show it to the user, forcing them to enter player names. The exec() function doesn't return until the dialog is accepted or cancelled. If the dialog was canceled, we abandon the creation of a new game. Otherwise, we ask the dialog for player names and set them on appropriate labels. Finally, we initialize the board so that users can play the game. The dialog object was created without the new keyword, so it will be deleted immediately after this.
Now you can run the application and see how the configuration dialog works.