How to display text in main window?

the_prole picture the_prole · Dec 5, 2014 · Viewed 15.7k times · Source

I'm new to Qt and I'm having a hard time finding a simple example illustrating how to display some text on the main window. For example, I just want to save some text in a string and display the contents on the main window. I thought to do something like this in the mainwindow.cpp but to no avail.

this->setText("Hello, world!\n");

Answer

lpapp picture lpapp · Dec 5, 2014

Do e.g. this in your mainwindow constructor:

#include <QLabel>
...
QLabel *label = new QLabel(this);
label->setText("first line\nsecond line");

There are various ways to display something like that, this is naturally just one of those, but it should get you going.

Here is a simple example showing this without a custom QMainWindow subclass:

main.cpp

#include <QLabel>
#include <QMainWindow>
#include <QApplication>

int main(int argc, char **argv)
{
    QApplication application(argc, argv);
    QMainWindow mainWindow;
    QLabel *label = new QLabel(&mainWindow);
    label->setText("first line\nsecond line");
    mainWindow.show();
    return application.exec();
}

main.pro

TEMPLATE = app
TARGET = main
QT += widgets
SOURCES += main.cpp

Build and Run

qmake && make && ./main