Search code examples
c++qtalignmentqlineeditqlabel

horizontally Aligning dynamically created widgets qt c++


The following code is used by me to dynamically generate a QLabel and QLineEdit(vertically) based on a QStringList(named newList) !

for(int i=0;i<newList.size();i++)
{
      QlineEdit *a=new QLineEdit();
      QLabel *b= new QLabel();

      ui->verticalLayout->addWidget(a);
      ui->verticalLayout_2->addWidget(b);

      b->setText(newList[i]);
}

Both the labels and line edits are generated and the items of the string list is depicted in the labels!But the problem I face is that label corresponding to each line edit is not alligned horizontally with that line edit! How can I correct this?


Solution

  • You can put the LineEdit and Label in a QFrame and than put the QFrame in the vertical Layout. Or you use a horizontal layout for LineEdit and Label and put this to the vertical layout.

    edit: (not tested and only write quickly!)

    for(int i=0;i<newList.size();i++)
    {
          QFrame *f = new QFrame();  
          QlineEdit *a=new QLineEdit( f );
          QLabel *b= new QLabel( f );
    
    
          ui->verticalLayout->addWidget(f);
    
          b->setText(newList[i]);
    }
    

    Exampels for different ways in comparison