How to display text in main window?

18,484

Solution 1

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

Solution 2

You need a QLabel somewhere in the mainWindow and then do

label->setText("Hello, world!");

Then the text will appear in the label.

Solution 3

All widgets derive from the same base class, QWidget, which can be displayed with a call to show()

Therefore, at its most basic level, Qt allows you to create any widget and display it with minimal code, without even having to explicitly declare a main window: -

#include <QApplication>
#include <QLabel>

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

    QLabel *label = new QLabel(&mainWindow);
    label->setText("Hello World");
    label->show();

    return app.exec(); // start the main event loop running
}

Following on from this, each Widget can be provided with a parent widget, allowing the QLabel to be added to MainWindow (or any other widget), as shown by the answer provided by @lpapp

Share:
18,484
the_prole
Author by

the_prole

Updated on June 06, 2022

Comments

  • the_prole
    the_prole almost 2 years

    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");