Search code examples
c++qtqwidgetqmainwindow

How to add a custom widget to the main window in Qt Creator


I am new to Qt. I took an example from here http://doc.qt.io/qt-5/qtmultimediawidgets-player-example.html. Now I want to integrate the player in the main window. I created a Qt Widgets application project, I thought, that I would just have to edit the main window code:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    Player* player;
    MainWindow::setCentralWidget(player);

}

But it doesn't work and I get the following error:

Starting /home/***/Documents/build-player-Desktop-Debug/player... The program has unexpectedly finished.

/home/***/Documents/build-player-Desktop-Debug/player crashed

How can I integrate a custom widget which is written in code, without ui in a main window? Thank you in advance.


Solution

  • In your own MainWindow class you can add a widget to the layout of that MainWindow:

    MyMainWindow::MyMainWindow(QWidget *parent) :
        ...
    {
        this->ui->setupUi(this);
    
        QLabel *myLabel = new QLabel();
    
        this->layout()->addWidget(myLabel);
    }