This code which does not dynamically allocate memory, does not show any label on the window.
That's because the label goes out of scope as soon as you return from the constructor. The label's lifetime is annotated below. The label
is a QLabel
itself.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QLabel label; // label is born
label.setText ("cdsadsaf"); // label is alive
label.setParent (this); // label is alive
} // label dies
After dynamically allocating memory, the label shows up.
That's because the label doesn't go out of scope. The pointer to it does, but that doesn't matter. Note that label
is merely a pointer, and the QLabel
object exists independently of the pointer to it.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QLabel *label = new QLabel(this); // label is born, QLabel is born
label->setText("first line\nsecond line"); // label is alive, QLabel is alive
} // label dies, QLabel is alive
Why is dynamic memory allocation necessary for QLabel to work?
It's not. You happened to give the QLabel
a chance to stay alive as a consequence of using dynamic allocation, but that's just a coincidence.
You can make the label a part of the parent object itself - it won't necessitate a separate allocation then. The compiler will manage the memory for you.
#include <QtWidgets>
class MainWindow : public QMainWindow {
QWidget m_central;
QGridLayout m_layout{&m_central};
QLabel m_label{"Hello, World"};
public:
MainWindow(QWidget * parent = {}) : QMainWindow{parent} {
m_layout.addWidget(&m_label, 0, 0);
setCentralWidget(&m_central);
}
};
int main(int argc, char ** argv) {
QApplication app{argc, argv};
MainWindow w;
w.show();
return app.exec();
}