Synchronizing width of 2 (or more) QGridLayout(s)



  • I have here some window with a QTabWidget and a few tabs. Each tab contains various fields which are positioned with a QGridLayout. Always a pair of QLabel and some input field. Since the text of those QLabels have different length, the first column of those QGridLayouts position those input fields different. Is there some way to get those in sync, so that switching the tab does not cause the inputfields to "jump"?

    Short Example:

    #include <QtCore/QtCore>
    #include <QtGui/QtGui>
    #include <QtWidgets/QtWidgets>
    
    int main(int argc, char *argv[])
    {
      QApplication a(argc, argv);
    
      QTabWidget *tabW = new QTabWidget();
      QWidget *w1 = new QWidget(tabW);
      tabW->addTab(w1, "Tab 1");
      QGridLayout *g1 = new QGridLayout(w1);
      g1->addWidget(new QLabel("Short:", w1), 0, 0);
      g1->addWidget(new QLineEdit(w1), 0, 1);
    
      QWidget *w2 = new QWidget(tabW);
      tabW->addTab(w2, "Tab 2");
      QGridLayout *g2 = new QGridLayout(w2);
      g2->addWidget(new QLabel("Longer Text:", w2), 0, 0);
      g2->addWidget(new QLineEdit(w2), 0, 1);
    
      tabW->show();
      a.exec();
    
      return 0;
    }
    

  • Qt Champions 2016

    Hi @Wurgl,
    Use QFormLayout instead of a grid layout and try playing with the growth policy.

    Kind regards.



  • This code seems to work (just the block at the end is added).

    But I am still wondering, is my problem is a special one that is not needed by anyone else or might it be a general one?

    "Jumping" fields may happen with QStackedLayout too?

    However: Solved for me.

    #include <QtCore/QtCore>
    #include <QtGui/QtGui>
    #include <QtWidgets/QtWidgets>
    
    int main(int argc, char *argv[])
    {
      QApplication a(argc, argv);
    
      QTabWidget *tabW = new QTabWidget();
      QWidget *w1 = new QWidget(tabW);
      tabW->addTab(w1, "Tab 1");
      QGridLayout *g1 = new QGridLayout(w1);
      g1->addWidget(new QLabel("Short:", w1), 0, 0);
      g1->addWidget(new QLineEdit(w1), 0, 1);
    
      QWidget *w2 = new QWidget(tabW);
      tabW->addTab(w2, "Tab 2");
      QGridLayout *g2 = new QGridLayout(w2);
      g2->addWidget(new QLabel("Longer Text:", w2), 0, 0);
      g2->addWidget(new QLineEdit(w2), 0, 1);
    
      int maxWidth = 0;
      for(int row = 0; row < g1->rowCount(); ++ row)
        maxWidth = qMax(g1->itemAtPosition(row, 0)->minimumSize().width(), maxWidth);
      for(int row = 0; row < g2->rowCount(); ++ row)
        maxWidth = qMax(g2->itemAtPosition(row, 0)->minimumSize().width(), maxWidth);
      g1->setColumnMinimumWidth(0, maxWidth);
      g2->setColumnMinimumWidth(0, maxWidth);
    
    
      tabW->show();
      a.exec();
    
      return 0;
    }
    
    

Log in to reply
 

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