[SOLVED] Add widgets manually to Qt designer generated code



  • Hello,

    First: I stated using qt yesterday so be easy on me please.
    I created a simple layout with designer and now I want to add new widgets to it manually, but as I see it looks impossible, since there is no "redraw" or such. Is there any way to do it, apart from copying the code from setupUi and discarding the gui design?

    Here is what I'm doing:
    @ ui->setupUi(this);

    MapArea wtf;
    QScrollArea *sa = new QScrollArea();
    sa->setWidget(&wtf);
    QVBoxLayout *bl = new QVBoxLayout(ui->widget);
    bl->addWidget(sa);
    QTextEdit *te = new QTextEdit();
    bl->addWidget(te);
    ui->widget->setLayout(bl);
    //and now something here to redraw the window with the new widgets
    

    @

    thanks
    david



  • Hi,

    Since you have already created your QMainWindow in the designer you can write the following code in your constructor:

    @MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);
    QLabel *lblFirstName = new QLabel("First Name");
    QLabel *lblLastName = new QLabel("Last Name");

    QLineEdit *txtFirstName = new QLineEdit();
    QLineEdit *txtLastName = new QLineEdit();
    
    QPushButton *btnOk = new QPushButton("OK");
    QPushButton *btnCancel = new QPushButton("Cancel");
    
    QHBoxLayout *top = new QHBoxLayout;
    QHBoxLayout *bottom = new QHBoxLayout;
    QHBoxLayout *btnLayout = new QHBoxLayout;
    
    top->addWidget(lblFirstName);
    top->addWidget(txtFirstName);
    
    bottom->addWidget(lblLastName);
    bottom->addWidget(txtLastName);
    
    btnLayout->addStretch();
    btnLayout->addWidget(btnOk);
    btnLayout->addWidget(btnCancel);
    
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(top);
    mainLayout->addLayout(bottom);
    mainLayout->addLayout(btnLayout);
    
    this->centralWidget()->setLayout(mainLayout);
    

    }@

    This is just an example to add widgets programatically. It shows user information with some buttons. You can start with the basics provided on internet and also "Books":http://qt-project.org/books on Qt.



  • Thanks, my bad... (cause I've just did the same thing you wrote). The actual problem was that I already set a layout for the 'widget' component and I tried to add a new one in the code above, thus nothing happened. Now with this, it works (compare to the original code snippet):
    @
    ui->setupUi(this);

    MapArea wtf;
    QScrollArea *sa = new QScrollArea();
    sa->setWidget(&wtf);
    QTextEdit *te = new QTextEdit();
    ui->widget->layout()->addWidget(sa);
    ui->widget->layout()->addWidget(te);
    

    @



  • You are welcome !!!!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.