简体   繁体   English

如何在 Qt Creator 的主窗口中添加自定义小部件

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

I am new to Qt.我是 Qt 的新手。 I took an example from here http://doc.qt.io/qt-5/qtmultimediawidgets-player-example.html .我从这里举了一个例子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:我创建了一个 Qt Widgets 应用程序项目,我想,我只需要编辑主窗口代码:

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... 程序意外完成。

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

How can I integrate a custom widget which is written in code, without ui in a main window?如何在主窗口中没有 ui 的情况下集成用代码编写的自定义小部件? 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.我通常在设计器中将 QWidget(或我要扩展的任何小部件类型)添加到我的 .ui 文件中,然后将其提升为实际的派生类型。 See the Qt docs for more info on promoting widgets .有关推广小部件的更多信息,请参阅Qt 文档 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.这意味着我可以像往常一样设置基本小部件的属性并设计窗口,但在实例化 UI 时仍然获得我的特殊类的实例。

In your own MainWindow class you can add a widget to the layout of that MainWindow :在您自己的MainWindow类中,您可以向该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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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