简体   繁体   中英

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.

Well, player can't be placed on the window if it is not initialized. Write something like that :

Player *player = new Player();

I usually add a QWidget (or whatever widget type I'm extending) to my .ui-file in the designer and then promote it to the actual derived type. See the Qt docs for more info on promoting widgets . This means that I can set the base widget's properties and design the window as usual but still get an instance of my special class when the UI is instantiated.

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);
}
MainWindow:MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    SomeStupidWidget *ssw = new SomeStupidWidget(this); /* important! don't forget about passing "this" as argument, otherwise this could cause a memory leak(Qt handles object's lifetime by means of it's "owner" mechanism)*/

    layout()->addWidget(ssw);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM