qt/ledset/table.cpp
2022-09-07 23:10:35 +08:00

34 lines
1.7 KiB
C++

#include "table.h"
Table::Table(std::initializer_list<ColAttr> colAttrs, QWidget *parent) : QTableWidget{0, (int)colAttrs.size(), parent} {
int i = 0;
for(typename std::initializer_list<ColAttr>::const_iterator it = colAttrs.begin(); it != colAttrs.end(); ++it) {
auto item = horizontalHeaderItem(i);
if(item==0) setHorizontalHeaderItem(i, item = new QTableWidgetItem());
item->setText(it->text);
item->setData(0x99, it->width);
if(it->width > 0) horizontalHeader()->resizeSection(i, it->width);
else if(it->width < 0) {
if(it->width == Stretch) horizontalHeader()->setSectionResizeMode(i, QHeaderView::Stretch);
if(it->width == ResizeToContents) horizontalHeader()->setSectionResizeMode(i, QHeaderView::ResizeToContents);
}
mFieldMap.insert(it->field, i++);
}
}
int Table::sizeHintForColumn(int column) const {
auto item = horizontalHeaderItem(column);
if(item==0) return QTableWidget::sizeHintForColumn(column);
int width = item->data(0x99).toInt();
if(width==0) return QTableWidget::sizeHintForColumn(column);
auto header = horizontalHeader();
if(header->sectionResizeMode(column)!=QHeaderView::ResizeToContents) return QTableWidget::sizeHintForColumn(column);
int colCnt = columnCount();
int remainWidth = header->width(), stretchWidth = width;
for(int cc=0; cc<colCnt; cc++) if(cc!=column && (item = horizontalHeaderItem(cc))) {
if(header->sectionResizeMode(cc)==QHeaderView::ResizeToContents) stretchWidth += item->data(0x99).toInt();
else remainWidth -= item->data(0x99).toInt();
}
if(remainWidth<=0) return QTableWidget::sizeHintForColumn(column);
return width * remainWidth / stretchWidth;
}