Important: Please read the Qt Code of Conduct -

How to add a custom widget manually(in code) to QMainWindow

  • Hi. I have run into a probleam that I can't add my custom widget manually to QMainWindow.
    I originally designed and add it to QMainWindow as this video

    But I now want to add my widget in code to have more flexibility. But how?
    I tried
    layout()->addWidget(trackEditor);//how I do that in QT4

    But it gave me
    QMainWindowLayout::addItem: Please use the public QMainWindow API instead

    how can I do this in QT5?


  • Welcome to DevNet!

    Take a look on Qt5 widgets examples.

    TrackEditor* trackEditor = new TrackEditor;
    QVBoxLayout *layout = new QVBoxLayout;

  • Try like this:

    Change 'mainLayout' to actually name of your layout.

  • Thanks, that works. But is there any way to add the widget without using QLayout? I prefer setting the location of my widget using x and y.

    Thanks for helping.

  • bq. But is there any way to add the widget without using QLayout?

    Yes, just set widget as parent. For example:
    MyWidget *myWidget = new MyWidget(ui->mainWidget)

    But, using layouts is more properly for many reasons.

Log in to reply