Rareform
Rareform

Reputation: 197

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.

Upvotes: 2

Views: 29044

Answers (4)

Armin Fisher
Armin Fisher

Reputation: 410

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);
}

Upvotes: 0

goulashsoup
goulashsoup

Reputation: 3116

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);
}

Upvotes: 4

user408952
user408952

Reputation: 932

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.

Upvotes: 2

La masse
La masse

Reputation: 1190

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

Player *player = new Player();

Upvotes: 3

Related Questions