class MyWidget : public QWidget { public:
MyWidget( QWidget *parent=0, const char *name=0 ); };
MyWidget::MyWidget( QWidget *parent, const char *name )
: QWidget( parent, name ) {
QPushButton *quit = new QPushButton( "Quit", this, "quit" );
quit->setGeometry( 62, 40, 75, 30 );
quit->setFont( QFont( "Times", 18, QFont::Bold ) );
}
In the above code quit
is allocated in Heap and it is necessary since it is child of MyWidget
Why does Qt needs allocate of child objects in the Heap?
In your example quit doesn't have to be heap allocated.
This code compiles and executes fine:
struct MyWidget : QWidget
{
QPushButton quit;
MyWidget()
{
quit.setGeometry( 62, 40, 75, 30 );
quit.setFont( QFont( "Times", 18, QFont::Bold ) );
}
};
If I understand what you're asking correctly, I think it mostly boils down to tradition and example, with a little bit of header-dependency thrown in.
The alternative, of course, is to declare quit
as a member variable of MyWidget
. If you do this, then you would need to include the header file for QPushButton
where MyWidget
is declared, instead of in the implementation file. The example you gave also relies on the parent-relationship of QObject
s to keep track of the memory for the button, and delete it on destruction, so it doesn't need to be specified as a member in the class.
I'm pretty sure you could change to stack allocation if you really wanted to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With