[SOLVED]problem with setCentralWidget
-
Hi,
in my main window I've got the following piece of code that works:@void MainWindow::setDefaultCentralWidget()
{
QLabel* defaultCentralWidget = new QLabel( this );
defaultCentralWidget->setPixmap( QPixmap( ":/logo/img/logo/logo.png") );
defaultCentralWidget->setAlignment( Qt::AlignCenter );
setCentralWidget( defaultCentralWidget );
}@and every time I call it works. Now, thinking that creating a new label each time could be a waste of resources, I tried to modify it as follows:
@void MainWindow::setDefaultCentralWidget()
{setCentralWidget( defaultCentralWidget );
}@
making defaultCentralWidget a label within the MainWindow class, created into the class constructor:
@
MainWindow::MainWindow( QWidget parent* ){defaultCentralWidget = new QLabel( this ); defaultCentralWidget->setPixmap( QPixmap( ":/logo/img/logo/logo.png") ); defaultCentralWidget->setAlignment( Qt::AlignCenter );
}
@but this works only for the first call, while at the second call the application crashes. What am I missing here?
-
You possibly have to delete the old pointers content, where defaultCentralWidget is pointing to before you allocate new space for the second QLabel Object?
And of course the defaultCentralWidget should be declared in the header as well, since it must be visible to the setDefaultCentralWidget Method.
Which error message is thrown?
-
When passing a widget to setCentralWidget() QMainWindow takes ownership of the widget. This means, that any call to setCentralWidget() will delete the current central widget and set the provided widget as the new central widget. -When you pass the same widget twice it might be deleted as it is the current central widget and there is obviously no check if the provided widget is already set as the central widget.-
However, this means that you will have to create a new widget every time you have set another central widget then your defaultCentralWidget as it will get deleted by QMainWindow.
In addition you are missing a call to the QWidget base class constructor.
@
MainWindow::MainWindow(QWidget* parent) : QWidget(parent)
{
...
}
@ -
[quote author="Lukas Geyer" date="1318403103"]When passing a widget to setCentralWidget() QMainWindow takes ownership of the widget. This means, that any call to setCentralWidget() will delete the current central widget and set the provided widget as the new central widget. [/quote]
Thanks, I had an hint about that, now I'm sure that the widget is deleted.
By the way, the constructor has not call to base widget since I have edited it in place, not cut and paste! -
Well, I took a quick look at the sources and in fact the central widget is only deleted if the new central widget is actually different from the current central widget. This means the subsequent calls to setCentralWidget() using the same widget will work.
So the problem only arises if you pass another central widget before passing the current central widget again (as in your case).