3

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");
László Papp
  • 51,870
  • 39
  • 111
  • 135
the_prole
  • 8,275
  • 16
  • 78
  • 163

3 Answers3

7

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
László Papp
  • 51,870
  • 39
  • 111
  • 135
1

You need a QLabel somewhere in the mainWindow and then do

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

Then the text will appear in the label.

nick_g
  • 489
  • 1
  • 7
  • 15
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
1

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

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85