Reputation: 8955
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");
Upvotes: 3
Views: 24617
Reputation: 48216
You need a QLabel
somewhere in the mainWindow
and then do
label->setText("Hello, world!");
Then the text will appear in the label
.
Upvotes: 1
Reputation: 27611
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
Upvotes: 1
Reputation: 53175
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:
#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();
}
TEMPLATE = app
TARGET = main
QT += widgets
SOURCES += main.cpp
qmake && make && ./main
Upvotes: 7