Change Label Color in Qt Game Tutorial

How to change label color in Qt with a simple game example using C++ and Qt Creator. Build a heads or tails coin toss game in this tutorial.

The image below shows the simple game built in this part of the Qt programming tutorial series. It is an enhanced version of the simple coin toss game from part 7 of this tutorial series.

Change Label Color in Qt Heads or Tails Coin Toss Game
Change Label Color in Qt Heads or Tails Coin Toss Game

In this game, the player selects either heads or tails using the radio buttons at the left. The player then clicks the button at the bottom of the window to simulate a coin toss. If the coin toss result matches the selection from the player, the player wins the game.

Part 14 of the Qt Creator C++ Tutorial

Go to the Qt Programming Tutorial Series Table of Contents

Change Label Color in Qt and Other Lessons

Although the coin toss game built in this tutorial is very simple, it teaches several new Qt concepts. The following list shows some of the new things that you will learn.

  • How to make a Qt window a fixed size and stop the user from resizing it.
  • Hide and show a widget, in this case a QPushButton.
  • How to disable and enable a widget.
  • Additional widget layout techniques.
  • How to deselect all radio buttons in a group.
  • Change label color in Qt as well as other label attributes.
  • How to change label attributes in Qt Creator.

Heads or Tails Qt Game Tutorial Steps

Follow the tutorial steps below to build the heads or tails game using Qt Creator and C++.

1. Create a New Qt Creator Widgets Application Project

Start Qt Creator. Create a new Qt Widgets Application project called heads_tails. If you have been following this tutorial series, you will know how to do this.

2. Lay Out the Game Window

In Qt Creator, change to Design mode by opening the mainwindow.ui file.

2.1 Delete Unneeded Widgets

Delete the status bar, toolbar and menu bar from the main window.

2.2 Change the Window Title

With the main window selected, change its title to Heads or Tails using the bottom right pane in Qt Creator. This is done at the windowTitle item under the QWidget heading.

2.3 Size and Fix the Window

The following steps show how to set the size of the window and fix it so that the user can’t change its size.

2.3.1 Set Default Window Size

With the main window still selected, find the geometry item under QWidget in the bottom right pane. Expand the geometry item and then change Width to 580 and Height to 240. This sets the initial size of the window to these dimensions.

2.3.2 Fix the Window Size

Now change the Width and Height parameters of both the minimumSize and maximumSize to the same dimensions. This fixes the window size so that the user can not change its size.

2.4 Place the Main Layout Widgets

In the main window, from top to bottom, place a Grid Layout widget, and then two Horizontal Layout widgets.

Right-click the main window and select Lay out at the bottom of the menu that pops up. Then select Lay Out in a Grid from the pop-out sub-menu.

2.5 Place Widgets in Top Layout

Place the following widgets in the top layout, which is a Grid Layout.

2.5.1 Place 5 Labels and 1 Vertical Layout

From left to right, top to bottom, place the following widgets. Three Label widgets at the top. Below these widgets, a Vertical Layout, followed by two Label widgets. To place the widgets in the desired position in the Grid Layout, drag each widget to either the right edge or bottom edge. A highlighted blue line appears where the widget is placed when the mouse button is released.

2.5.2 Place 2 Radio Buttons

Place two Radio Button widgets in the Vertical Layout that was placed in the previous step. At this stage the window layout should look as follows.

Qt Window Widget Layout
Qt Window Widget Layout
2.5.3 Change Widget Text

Change the text of the top 3 widgets from left to right to the following.

  • Place Bet, Then Toss Coin
  • Your Bet:
  • Coin Toss Result:

Use the font item under QWidget in the bottom right pane to change these labels to Bold.

Change the top radio button objectName under QObject to rbHeads and its text to Heads.

Do the same for the second radio button by changing objectName to rbTails and text to Tails.

Change the objectName and text of the labels to the right of the radio buttons to lblYourBet and Heads or Tails? for the first. Change the second to lblTossResult and Heads or Tails? for the second.

2.6 Place Widgets in Middle Layout

Place a Label widget in the middle layout box. Place a Horizontal Spacer on either side of the label.

Change the label widget objectName to lblWinLose and text to Will You Win or Lose?

Find font under QWidget and expand it. Change the Point Size to 16 and check the Bold item.

2.7 Place Widgets in Bottom Layout

Place two Push Button widgets in the bottom layout widget. Place a Horizontal Spacer on each side of the buttons.

Change the left button objectName to btnToss and its text to Toss Coin.

Change the right button objectName to btnPlayAgain and its text to Play Again.

2.8 Change Default Widget States

When the game starts, the Play Again button must be hidden and the Toss Coin button disabled. The Toss Coin button will be enabled only after the player selects either Heads or Tails.

Select the Toss Coin button. Under QWidget, uncheck enabled.

The Play Again button will be hidden programmatically in the constructor of the main window.

At this stage, the window layout should look as follows.

Heads or Tails Game Widget Layout in Qt Creator
Heads or Tails Game Widget Layout in Qt Creator

2.9 Group the Radio Buttons

In order to access the radio buttons as a group in the C++ code, the radio buttons must be grouped.

First select both radio buttons. To do this, click the top radio button, hold down the Ctrl key and then click the bottom radio button. Right click one of the selected radio buttons. Select Assign to button group → New button group on the menu that pops up. This adds a new QButtonGroup to the project called buttonGroup.

3. Add Qt Slots

We now add four slot functions for the following widget signals.

  • Heads radio button clicked signal.
  • Tails radio button clicked signal.
  • Toss Coin push button clicked signal.
  • Play Again push button clicked signal.

To add a slot for each of the above signals, first right-click on the desired widget. Click Go to slot… on the pop-up menu. Make sure that the clicked() signal is selected in the dialog box that opens. Click the OK button.

4. Write the C++ Code and Change Label Color in Qt

Modify the mainwindow.cpp file to add the code shown in the following listing.

mainwindow.cpp

#include <QTime>
#include <QString>
#include <QTextStream>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Hide the Play Again button at startup
    ui->btnPlayAgain->hide();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_rbHeads_clicked()
{
    // Enable the Toss Coin Button when Heads radio button checked
    ui->btnToss->setEnabled(true);
}

void MainWindow::on_rbTails_clicked()
{
    // Enable the Toss Coin Button when Tails radio button checked
    ui->btnToss->setEnabled(true);
}

// Toss Coin button clicked
void MainWindow::on_btnToss_clicked()
{
    qint32 rand_num;        // Random number to generate coin toss
    QString str;            // Utility string
    const char* red_text = "QLabel{color: red;}";
    const char* grn_text = "QLabel{color: green;}";

    // Time to seed random number generator
    QTime time = QTime::currentTime();

    // Initialize random number generator using time in milli-seconds as seed
    qsrand(time.msec());
    // Generate a the random number between 0 and 1
    rand_num = qrand() % 2;

    // Set string text to heads or tails
    QTextStream(&str) << (rand_num ? "Heads" : "Tails");
    // Update result string with Heads or Tails text from string
    ui->lblTossResult->setText(str);

    // Is the Heads radio button checked?
    if (ui->rbHeads->isChecked()) {
        ui->lblYourBet->setText("Heads");                           // Update the bet text label
        str.clear();                                                // Clear utility string for reuse
        QTextStream(&str) << (rand_num ? "You Win!" : "You Lose!"); // Determine if player won or lost
        ui->lblWinLose->setText(str);                               // Update win/lose string with game result
        str.clear();
        // Set text color to green for win, or red for lose
        QTextStream(&str) << (rand_num ? grn_text : red_text);
        ui->lblWinLose->setStyleSheet(str);
    }
    // Is the Tails radio button checked?
    else if (ui->rbTails->isChecked()) {
        ui->lblYourBet->setText("Tails");
        str.clear();
        QTextStream(&str) << (rand_num ? "You Lose!" : "You Win!");
        ui->lblWinLose->setText(str);
        str.clear();
        QTextStream(&str) << (rand_num ? red_text : grn_text);
        ui->lblWinLose->setStyleSheet(str);
    }

    // Hide Toss Coin button, show Play Again button
    ui->btnToss->hide();
    ui->btnPlayAgain->show();
    // Disable radio buttons so values can't be changed
    ui->rbHeads->setEnabled(false);
    ui->rbTails->setEnabled(false);
}

// Play Again button clicked, reset the game to startup conditions
void MainWindow::on_btnPlayAgain_clicked()
{
    // Uncheck both radio buttons
    ui->buttonGroup->setExclusive(false);
    ui->rbHeads->setChecked(false);
    ui->rbTails->setChecked(false);
    ui->buttonGroup->setExclusive(true);
    // Enable radio buttons
    ui->rbHeads->setEnabled(true);
    ui->rbTails->setEnabled(true);

    // Show and disable Toss Coin button, hide Play Again button
    ui->btnToss->show();
    ui->btnPlayAgain->hide();
    ui->btnToss->setEnabled(false);

    // Reset the text in the labels
    ui->lblWinLose->setText("Will You Win or Lose?");
    ui->lblTossResult->setText("Heads or Tails?");
    ui->lblYourBet->setText("Heads or Tails?");
    // Reset win/lose label to black
    ui->lblWinLose->setStyleSheet("QLabel{color: black;}");
}

The above code listing makes the following changes to the code in the mainwindow.cpp file.

4.1 Include Header Files

Include three header files at the top of the file as follows.

#include <QTime>
#include <QString>
#include <QTextStream>

4.2 Hide the Play Again Button

Hide the Play Again button in the MainWindow class constructor. Add the the line shown below to programmatically hide the button.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Hide the Play Again button at startup
    ui->btnPlayAgain->hide();
}

Hide the Play Again button by accessing it through the ui pointer and calling the hide() method.

4.3 Radio Button Slots

When the player selects either the Heads or Tails radio button, the Toss Coin button is enabled. Do this by calling the setEnabled() method of the Toss Coin button and passing it true, as shown below. Call the same method from both radio button slots.

void MainWindow::on_rbHeads_clicked()
{
    // Enable the Toss Coin Button when Heads radio button checked
    ui->btnToss->setEnabled(true);
}

void MainWindow::on_rbTails_clicked()
{
    // Enable the Toss Coin Button when Tails radio button checked
    ui->btnToss->setEnabled(true);
}

4.4 Toss Coin Slot

The toss coin slot generates a random number between 0 and 1 to simulate a coin toss. It then checks which radio button is selected and determines whether the player wins or loses the game.

It also takes care of the logic in the game to enable and disable, and show and hide the correct widgets as needed.

4.5 How to Change Label Color in Qt

The way used to change label color in Qt is to call the setStyleSheet() method of the QLabel and pass it a CSS type string that specifies the color. The following code snippet show an example of this.

// Set text color to green for win, or red for lose
QTextStream(&str) << (rand_num ? grn_text : red_text);
ui->lblWinLose->setStyleSheet(str);

The text strings assigned to the str string can be found at the top of the slot method. These strings are shown in the following code.

const char* red_text = "QLabel{color: red;}";
const char* grn_text = "QLabel{color: green;}";

See the Qt style sheet reference for more information on the style properties that can be changed for various widgets.

4.6 Play Again Button Slot and Change Label Color in Qt to Default

Finally the slot function or method for the Play Again button resets the game by resetting all the widgets to their default states.

The label color is reset to black. This time a string is passed directly to the setStyleSheet() method of the QLabel widget as shown below.

// Reset win/lose label to black
ui->lblWinLose->setStyleSheet("QLabel{color: black;}");

Leave a Reply

Your email address will not be published. Required fields are marked *