Reputation: 79625
I'm creating a column tracking layout that inherits from QHBoxLayout, which will align a couple of line edits to the table columns:
To do that, I calculate the absolute screen position of each section size in ColumnAlignedLayout::setGeometry()
using this code:
void ColumnAlignedLayout::setGeometry(const QRect &r)
{
QHBoxLayout::setGeometry(r);
int widgetX = parentWidget()->mapToGlobal(QPoint(0, 0)).x();
int headerX = headerView->mapToGlobal(QPoint(0, 0)).x();
int delta = headerX - widgetX;
for (int ii = 0; ii < headerView->count(); ++ii) {
int pos = headerView->sectionPosition(ii);
int size = headerView->sectionSize(ii);
auto item = itemAt(ii);
auto r = item->geometry();
r.setLeft(pos + delta);
r.setWidth(size);
item->setGeometry(r);
}
}
The layout already works, except when the table has a horizontal scroll.
The full project is at https://github.com/sashoalm/ColumnAlignedLayout, and running it will reproduce the problem easily - just enlarge the columns until the horizontal scrollbar appears, and then scroll until the first column is hidden.
headerView->mapToGlobal(QPoint(0, 0)).x();
gives the same value whether the table has been resized or not.
I found a similar question but it's for objective C, and it doesn't account for scrolling which is my problem.
how to get the absolute position of a section header in tableview?
Upvotes: 0
Views: 890
Reputation: 79625
Eventually I went into Qt's source for their paint event, assuming they would need the actual position for it, and they use sectionViewportPosition()
, which gives the actual section position relative to the QTableWidget/QTableView's upper-left corner.
You can use that along with mapToGlobal()
to get the global horizontal position of the section.
Upvotes: 3