The 2nd way you present won't work since QLabel
is not copyable and thus the code won't compile. Perhaps you've meant
QLabel label{"bla"};
Furthermore, it has nothing to do with the stack at all. You could have written that line within a class:
class MyUi : public QWidget {
QGridLayout m_layout{this};
QLabel m_label{"bla"};
};
And, usually, you're supposed to do exactly that. You could of course allocate the widget as an automatic variable - usually this will only happen within main
:
int main(int argc, char **argv) {
QApplication app{argc, argv};
...
MyUi ui;
ui.show();
return app.exec();
}
Here you need to use some common sense. How big will that class really get? Note that all Qt classes that derive from QObject
use PIMPL and are either the size of a pointer, or the size of a couple of pointers - thus quite small.
In most cases, you shouldn't be worrying about it. If you run out of stack when your project gets truly huge, allocate MyUi
dynamically and that's all:
int main(int argc, char **argv) {
QApplication app{argc, argv};
...
auto ui = std::make_unique<MyUi>();
ui->show();
return app.exec();
}
I've never ran into that problem personally: if your MyUi
class is big enough, you've probably got serious issues with your design, and the class is way too monolithic and has too much responsibility.