最后一个空列填充QTableView

问题描述

QTableView中,我需要最后一列(最右边)为空,可扩展但不可移动。目的是使表格不要突然结束(因为我在行中使用了其他颜色)或很难向右扩展。在QHeaderView中有一个setFirstSectionMovable(bool);在最后一节中,我需要类似的内容,让其余部分可以移动。 (换句话说:用一个空白的不可移动列填充表格的其余部分)。任何线索如何实现这一目标?

我确实重写了mousepressEvent()的子类中的QHeaderView来跳过最后一节,但是仍然可以通过将其他列移到其位置来移动它,并且我不知道如何防止这种情况。 / p>

解决方法

AMOQ:

成为 HeaderView QHeaderView 的子类,并拥有

setSectionsMovable(true);
setStretchLastSection(true);

处理 sectionMoved 信号:

connect(this,&QHeaderView::sectionMoved,[this](int,int,int newVisual) {                
  if(newVisual == count()-1) { moveSection(newVisual,newVisual-1); }
});

覆盖 mousePressEvent

void HeaderView::mousePressEvent(QMouseEvent* event) {    
int logicalIdx = logicalIndexAt(event->pos());       
if(logicalIdx != count()-1) { QHeaderView::mousePressEvent(event); }
}