You will probably learn to allocate widget on the heap anyway.
You get the error because of the order in which the stack allocated objects get destructed when they get out of scope.
So you can do one of the following solutions:
1)
#include <QtGui>
int main(int argv, char **args)
{
QWidget window;
//create the window QWidget first, than the rest //... rest of the example, obviously don't let two copy of the: QWidget window; line
#include <QtGui>
int main(int argv, char **args)
{
QApplication app(argv, args);
QWidget window; //create the window QWidget first, than the rest
QTextEdit textEdit;
QPushButton quitButton("Quit");
//... rest of the example, obviously don't let two copy of the: QWidget window; line
To copy to clipboard, switch view to plain text mode
2) This is the recommended solution: Learn to use widgets on the heap, use pointers, allocate memory with new, and Qt parent-child relationship.
#include <QtGui>
int main(int argv, char **args)
{
QWidget* window
= new QWidget;
// this is how you allocate on the heap //the main window/widget can be allocated on the stack
QObject::connect(quitButton,
SIGNAL(clicked
()),
qApp,
SLOT(quit
()));
//note that you just write the name without & operator
layout->addWidget(textEdit); // -> this is the operator to access members if use pointers
layout->addWidget(quitButton);
window->setLayout(layout); //again without &, and all the widgets added to layout are child of window
window->show();
int r = app.exec(); //this is the proper way to free resources if you allocate the main window/widget om the heap
delete window;//here you free the memory for QWidget window, this will automatically delete the childs of window
return r;
}
#include <QtGui>
int main(int argv, char **args)
{
QApplication app(argv, args);
QWidget* window = new QWidget; // this is how you allocate on the heap
//the main window/widget can be allocated on the stack
QTextEdit *textEdit = new QTextEdit; //
QPushButton *quitButton = new QPushButton("Quit");
QObject::connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); //note that you just write the name without & operator
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(textEdit); // -> this is the operator to access members if use pointers
layout->addWidget(quitButton);
window->setLayout(layout); //again without &, and all the widgets added to layout are child of window
window->show();
int r = app.exec(); //this is the proper way to free resources if you allocate the main window/widget om the heap
delete window;//here you free the memory for QWidget window, this will automatically delete the childs of window
return r;
}
To copy to clipboard, switch view to plain text mode
Bookmarks