Есть задача: создать прямоугольное поле с чекбоксами. Для задачи идеально подходит QGridLayout
.
Строки и столбцы этого поля должны иметь заголовки (у столбцов - совсем узкие).
Размеры поля - 10 в ширину и 20 в высоту. В высоту это поле на форму не лезет, поэтому я добавил QScrollArea
и поместил QGridLayout
туда.
Хочется зафиксировать заголовок: добавляю QVBoxLayout
, помещаю туда ещё один QGridLayout
и эту QScrollArea
. В верхний grid помещаю виджеты с заголовками.
Пробегаюсь по всем item'ам, собираю макс.значение ширины из sizeHint().
И собственно проблема: за что надо "дёрнуть" grid'ы, чтобы выравнять ширину этих столбцов? В идеале ещё бы учесть ненулевую ширину рамки QScrollArea
...
Микро-приложение для демонстрации всего вышеизложенного:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
resize(200, 150);
auto * centralWidget = new QWidget (this);
setCentralWidget (centralWidget);
auto * mainLayout = new QVBoxLayout (centralWidget);
// header
auto * headerLayout = new QGridLayout ();
mainLayout->addLayout (headerLayout);
for (int column = 1; column < 5; column ++)
{
auto colName = QString ("%1").arg (column);
auto * hdr = new QLabel (colName, this);
headerLayout->addWidget (hdr, 0, column);
}
// items
auto * scrollArea = new QScrollArea (this);
mainLayout->addWidget (scrollArea);
auto * scrollContents = new QWidget (scrollArea);
scrollArea->setWidget (scrollContents);
auto * itemsLayout = new QGridLayout (scrollContents);
for (int row = 0; row < 15; row ++)
{
// row title
auto rowName = QString ("Row %1").arg (row);
auto * rowTitle = new QLabel (rowName, scrollContents);
itemsLayout->addWidget (rowTitle, row, 0);
// row contents
for (int column = 1; column < 5; column ++)
{
auto * item = new QCheckBox (scrollContents);
itemsLayout->addWidget (item, row, column);
}
}
scrollContents->adjustSize();
// adjust columns size
for (int col = 0; col < headerLayout->columnCount(); ++col)
{
int width = 0;
auto * item = headerLayout->itemAtPosition(0, col);
if (item)
width = item->sizeHint().width();
for (auto row = 0; row < itemsLayout->rowCount(); ++row)
{
auto * item = itemsLayout->itemAtPosition(row, col);
if (item)
width = qMax (width,
item->sizeHint().width() );
}
qDebug() << "fit width:" << col << width;
// FIXME this doesnt working!
//headerLayout->setColumnMinimumWidth (col, width);
//itemsLayout->setColumnMinimumWidth (col, width);
}
}
QTableView
? – alexis031182 15 фев '16 в 17:18