How to Select a Font in a Qt Widget Application in C++


In this article, we show how to select a font in a Qt widget application in C++.

This is a common feature in many software applications, including word processor software, to be able to modify the font, font style (regular, italic, bold, etc.), and font size of text.

We can add a font dialog box to a widget application so that we can change the font, font style, and font size.

This makes an application that is more professional and gives a user more options in the software.

Below is a Qt widget application that allows us to open a font dialog box and change the font.

Selecting a font in a qt widget in c++

You can see that we have opened up a file dialog box which allows a user to change the font.

Once a font is selected, when you go type in the textEdit element, you should see this changed font manifest.

So how do we do this in a Qt widget application?

So the first thing you have to do is create a Qt widget application.

You will have to place 1 textEdit element and 1 push button within this widget application.

We label one push button, 'Choose Font', as it functions to select a font. We give this element an objectName of 'chooseFontButton'.

With this, we now go to the heart of our code found in the 'widget.cpp' file.

Within this 'widget.cpp' file, we place the following contents shown below.

In order to open a font dialog box, we need the QFontDialog class.

We need the QFontDialog class in order to have the font dialog window open up when we click the 'Choose Font' button in our program. This allows us to select a different font.

So we create a function, void Widget::on_chooseFontButton_clicked(), which is executed when the 'Choose Font' button is clicked.

Within this function, we choose the font that a user enters.

We create a boolean integer, ok, which lets us know if a user selected a font.

We then create avariable, font, of type QFont, which gets a font from the font dialog box. Within this line, you can specify the default font, which in this case, is "Helvetica [Cronyx]" with a font size of 10. You can change this to any font that you want.

If the user successfully chooses a font, then we change the previous font to the font that the user selected in the textEdit element.

If you type now into the textEdit element, you should see this new font now appear with your text.

We can change the font, font style, and font size in a Qt widget application using the QFontDialog class.

And this is how to select a font in a Qt widget application in C++.

Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...