Skip to Content
Course content

228: Building a Simple Qt Application

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I actually get a window to show up without manually calculating pixel positions for every button?

If you've ever tried to build a GUI in older frameworks, you know the nightmare of hard-coding coordinates. You move one button five pixels to the left, and suddenly everything overlaps. In Qt, we avoid that entirely using Layout Managers. Instead of saying "put this button at (10, 50)", we tell Qt, "put these three widgets in a vertical column and distribute the space evenly."

For our example, we're building a simple Temperature Converter. I'll use a QVBoxLayout to stack our input field, our button, and our result label. Here is how you set up the basic structure:

#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QWidget window;
    window.setWindowTitle("TempConvert");

    // The layout handles the positioning for us
    QVBoxLayout *layout = new QVBoxLayout(&window);

    QLineEdit *inputField = new QLineEdit();
    inputField->setPlaceholderText("Enter Celsius...");
    
    QPushButton *convertButton = new QPushButton("Convert to Fahrenheit");
    QLabel *resultLabel = new QLabel("Result: --");

    layout->addWidget(inputField);
    layout->addWidget(convertButton);
    layout->addWidget(resultLabel);

    window.show();
    return app.exec();
}

Notice that I passed &window into the QVBoxLayout constructor. That tells the layout exactly which widget it's managing. I personally prefer this approach over calling window.setLayout(layout) just because it's a bit more concise.

How do I make the button actually do something when I click it?

This is where the "magic" of Qt happens: Signals and Slots. Think of a Signal as an event (like "I've been clicked!") and a Slot as the function that reacts to that event. You don't need to write complex listener interfaces; you just "connect" the signal to a function.

Since we are keeping this in a simple main function for now, we can use a C++ lambda as our slot. It keeps the logic right where the button is defined, which is great for small apps.

// Inside main, after creating the widgets...
QObject::connect(convertButton, &QPushButton::clicked, [=]() {
    bool ok;
    double celsius = inputField->text().toDouble(&ok);
    
    if (ok) {
        double fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
        resultLabel->setText("Result: " + QString::number(fahrenheit) + " °F");
    } else {
        resultLabel->setText("Please enter a valid number!");
    }
});

The [=] capture in the lambda is crucial here. It allows the lambda to access inputField and resultLabel from the surrounding scope. In a larger project, you'd likely move this logic into a member function of a QMainWindow class, but for a utility tool, lambdas are a lifesaver.

Do I have to use the Qt Designer drag-and-drop tool, or can I just write it in C++?

You'll see a lot of tutorials talking about .ui files and the "Designer" tool. It's a great tool for complex layouts, but I always recommend learning the C++ API first. Why? Because when something breaks in a generated ui_mainwindow.h file, you'll be totally lost if you don't understand how the object tree actually works.

Writing the GUI in code gives you absolute control. For instance, if you wanted to conditionally add a button only if the user is an administrator, doing that in code is a simple if statement. Doing it in the Designer requires you to manually find the pointer to the widget and call setVisible(false) anyway. Stick to the code until your window has so many widgets that you can't keep track of the layout in your head.




📋 Practical Task

Build a Simple BMI Calculator

Your task is to expand on the concepts from this lesson to create a Body Mass Index (BMI) Calculator application. Instead of just one input, you will need to manage multiple widgets and perform a slightly more complex calculation.

Requirements:

  • Create a window with two QLineEdit fields: one for weight (kg) and one for height (meters).
  • Add a QPushButton labeled "Calculate BMI".
  • Add a QLabel to display the final BMI result.
  • Use a QVBoxLayout to organize the widgets.
  • Implement the logic using a QObject::connect call with a lambda. The formula is: BMI = weight / (height * height).
  • Add a basic check to ensure the user doesn't enter zero for height to avoid a division-by-zero crash.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.