Game Programming using Qt 5 Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – Designing the game configuration dialog

First, select Add New... in the context menu of the tictactoe project and choose to create a new Qt Designer Form Class, as shown in the following screenshot:

In the window that appears, choose Dialog with Buttons Bottom:

Adjust the class name to ConfigurationDialog, leave the rest of the settings at their default values, and complete the wizard. The files that appear in the project (.cpp, .h, and .ui) are very similar to the files generated for the MainWindow class when we created our project. The only difference is that MainWindow uses QMainWindow as its base class, and ConfigurationDialog uses QDialog. Also, a MainWindow instance is created in the main function, so it shows when the application is started, while we'll need to create a ConfigurationDialog instance somewhere else in the code. QDialog implements behavior that is common for dialogs; in addition to the main content, it displays one or multiple buttons. When the dialog is selected, the user can interact with the dialog and then press one of the buttons. After this, the dialog is usually destroyed. QDialog has a convenient exec() method that doesn't return until the user makes a choice, and then it returns information about the pressed button. We will see that in action after we finish creating the dialog.

Drag and drop two labels and two line edits on the form, position them roughly in a grid, double-click on each of the labels, and adjust their captions to receive a result similar to the following:

Change the objectName property of the line edits to player1Name and player2Name. Then, click on some empty space in the form and choose the Layout in a grid entry in the upper toolbar. You should see the widgets snap into place—that's because you have just applied a layout to the form. Open the Tools menu, go to the Form Editor submenu, and choose the Preview entry to preview the form.