QMainWindow already has a layout.

The content area of a main window is called the central widget, see QMainWindow::setCentralWidget().

So if your code works in a widget, keep it there and set this widget as the central widget or add it to the actual central widget
Or use a QToolBar and add it to the main window.

Cheers,
_