You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout.
from http://doc.qt.io/qt-5.9/qwidget.html#setLayout
Which function is used for deleting the previous layout?
You just use
delete layout;
like you would with any other pointer you created using new
.