官术网_书友最值得收藏!

Time for action – adding properties to the board class

In this exercise, we will be adding a useful property to the board class. The property is going to hold information about the player who should make the next move. The type of the property is going to be the TicTacToeWidget::Player enumeration that we created earlier. For the getter and the setter methods, we are going to use the two functions that we created earlier: currentPlayer() and setCurrentPlayer().

Open the header file for our class and modify the class definition as shown in the following code:

class TicTacToeWidget : public QWidget {
  Q_OBJECT
 Q_ENUMS(Player)
 Q_PROPERTY(Player currentPlayer READ currentPlayer
 WRITE setCurrentPlayer
 NOTIFY currentPlayerChanged)
public:
  enum Player { Invalid, Player1, Player2, Draw };

What just happened?

Since we want to use an enumeration as a type of a property, we have to inform Qt's meta-object system about the enum. This is done with the Q_ENUMS macro. Then, we declare a property called currentPlayer and mark our two existing methods as getter and setter for the property. We also use the NOTIFY keyword to mark currentPlayerChanged as a signal that is sent to inform about a change in the value of the property. We won't be using this extra information in our small game, and we don't require currentPlayer to be a property at all, but it is always a good idea to try and find good candidates for properties and expose them because some day, someone might want to use our class in a way we hadn't predicted and a particular property might become useful.

主站蜘蛛池模板: 资溪县| 宁德市| 皋兰县| 嵊泗县| 阿勒泰市| 甘肃省| 墨竹工卡县| 陵川县| 文登市| 琼结县| 白城市| 乌鲁木齐市| 全州县| 京山县| 保定市| 兖州市| 措美县| 灵川县| 定陶县| 兴化市| 白银市| 正定县| 定安县| 金昌市| 攀枝花市| 昭苏县| 商河县| 哈巴河县| 三穗县| 麻城市| 定西市| 永康市| 堆龙德庆县| 娄底市| 崇文区| 宣恩县| 司法| 永福县| 江川县| 弥渡县| 岳西县|