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

Choosing between designer forms and plain C++ classes

One way of creating a custom widget is by adding a Designer Form Class to the project. Designer Form Class is a template provided by Qt Creator. It consists of a C++ class that inherits QWidget (directly or indirectly) and a designer form (.ui file), tied together by some automatically generated code. Our MainWindow class also follows this template.

However, if you try to use the visual form editor to create our tic-tac-toe board, you may find it quite inconvenient for this task. One problem is that you need to add nine identical buttons to the form manually. Another issue is accessing these buttons from the code when you need to make a signal connection or change the button's text. The ui->objectName approach is not applicable here because you can only access a concrete widget this way, so you'd have to resort to other means, such as the findChild() method that allows you to search for a child object by its name.

In this case, we prefer to add the buttons in the code, where we can make a loop, set up each button, and put them into an array for easy addressing. The process is pretty similar to how the designer forms operate, but we'll do it by hand. Of course, anything that the form editor can do is accessible through the API.

After you build the project, you can hold  Ctrl and click on ui_mainwindow.h at the beginning of mainwindow.cpp to see the code that actually sets up our main window. You should not edit this file, because your changes will not be persistent.