Search code examples
c++qtqwidgetqlayout

How to programmatically add a Qt widget (QPushButton, QTextEdit, QLabel) to a Qt Designer layout?


Is it possible to dynamically add widgets (PushButtons, Labels, etc.), into a Qt Designer-generated central widget layout? How can it be done?

Thank you!


Solution

  • Of course, and it's quite easy. You can have a look at the ui_mainwindow.h at the debug/release dir. I prefer setting layouts for widgets in QtDesigner to the code. It's something like this:

    //set layout programatically
    auto layout = new QHBoxLayout(ui->centralWidget());
    
    //or if you have set horizontalLayout in Qt Designer
    auto layout = dynamic_cast<QHBoxLayout*>(ui->centralWidget->layout());
    
    layout->addWidget(new QLabel("hello"));