Time for action – Reacting to the game board's signals

While writing a turn-based board game, it is a good idea to always clearly mark whose turn it is now to make a move. We will do this by marking the moving player's name in bold. There is already a signal in the board class that tells us that the current player has changed, which we can react to update the labels.

We need to connect the board's currentPlayerChanged signal to a new slot in the MainWindow class. Let's add appropriate code into the MainWindow constructor:

ui->setupUi(this);
connect(ui->gameBoard, &TicTacToeWidget::currentPlayerChanged,
        this, &MainWindow::updateNameLabels);

Now, for the slot itself, declare the following methods in the MainWindow class:

private:
void setLabelBold(QLabel *label, bool isBold);
private slots:
void updateNameLabels();

Now implement them using the following code:

void MainWindow::setLabelBold(QLabel *label, bool isBold)
{
    QFont f = label->font();
    f.setBold(isBold);
    label->setFont(f);
}

void MainWindow::updateNameLabels()
{
    setLabelBold(ui->player1Name,
        ui->gameBoard->currentPlayer() == 
TicTacToeWidget::Player::Player1); setLabelBold(ui->player2Name, ui->gameBoard->currentPlayer() ==
TicTacToeWidget::Player::Player2); }