I need to add a widget (QTableWidget) into QFileDialog's layout. I know that it is QGridLayout with sizes (3,4). The table must be in 3-rd row and span all columns.

QTableWidget* tableWidget = new QTableWidget(this);
QGridLayout *layout = static_cast<QGridLayout*>(QFileDialog::layout());
layout->addWidget(tableWidget, 2, 0, 1, 4);

With this code the original 3-rd row which contains lineEdit and save/open pushButton disappears. How can I add widgets between already existing widgets of QGridLayout so that original widgets remain in the layout.

有帮助吗?

解决方案

I strongly recommend you not to rely on QFileDialog's implementation. The layout can be different on different platforms or different versions of Qt. It may be more correct to place your table under the dialog or to the right of it. This can be done easily without altering the layout of the QFileDialog itself. Just create a QVBoxLayout and put QFileDialog and QTableWidget inside it.

However, the question has been asked, and the solution exists. QGridLayout has no functionality such as QBoxLayout::insertItem. So we need to implement this behavior manually. The plan is:

  1. Obtain the list of layout items placed in 3rd and 4th rows.
  2. Calculate new positions of items.
  3. Take elements out of item and add them back at new positions.

Working code:

QFileDialog* f = new QFileDialog();
f->setOption(QFileDialog::DontUseNativeDialog, true); //we need qt layout

QGridLayout *layout = static_cast<QGridLayout*>(f->layout());

QList< QPair<QLayoutItem*, QList<int> > > moved_items;
f->show();
for(int i = 0; i < layout->count(); i++) {
  int row, column, rowSpan, columnSpan;
  layout->getItemPosition(i, &row, &column, &rowSpan, &columnSpan);
  if (row >= 2) {
    QList<int> list;
    list << (row + 1) << column << rowSpan << columnSpan;
    moved_items << qMakePair(layout->takeAt(i), list);
    i--; // takeAt has shifted the rest items
  }
}

for(int i = 0; i < moved_items.count(); i++) {
  layout->addItem(moved_items[i].first,
      moved_items[i].second[0],
      moved_items[i].second[1],
      moved_items[i].second[2],
      moved_items[i].second[3]);
}

QTableWidget* tableWidget = new QTableWidget();
layout->addWidget(tableWidget, 2, 0, 1, 4);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top