Adan RH
Adan RH

Reputation: 65

QTableView Stretch Headers but keep Interactive

I am struggling triying to accomodate my QTableView to make it easy to the user.

This functions works as i really need:

ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

The issue with this is that the headers are not user adjustable anymore, are completely frozzen.

I know we also have this function which allows the user to adjust the Headers, but after using it, the headers go back as if i had not used QHeaderView::Stretch before:

ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);

I have really looked for this on many websites with no luck of finding a understandable answer for my level.

Thanks!

Upvotes: 2

Views: 1602

Answers (2)

PatriceC
PatriceC

Reputation: 1

use EventFilter likethis and install it on tablewidget last column default size must be knows (self.last_baseColumnSize)) :

def eventFilter(self,obj,event):
    if  obj is self.ui.tableWidget and event.type()==QEvent.Type.Resize:
        hub=self.ui.tableWidget.horizontalHeader()
        fixedSizes=self.ui.tableWidget.verticalHeader().width()
        fixedSizes+=self.ui.tableWidget.columnCount()+1 #Borders
        if (self.ui.tableWidget.verticalScrollBar().isVisible()):
            fixedSizes += self.ui.tableWidget.verticalScrollBar().width()
        tmp=[x for x in range(self.ui.tableWidget.columnCount()) if hub.resizeMode(x) != QHeaderView.Fixed]
        
        for i in range (self.ui.tableWidget.columnCount()-1):
            if hub.resizeMode(i) == QHeaderView.Fixed:
                fixedSizes+=self.ui.tableWidget.columnWidth(i)
        if hub.resizeMode(self.ui.tableWidget.columnCount()-1) == QHeaderView.Fixed:
            fixedSizes+=self.last_baseColumnSize
        
        newsize=max(20,(event.size().width()-fixedSizes)/len(tmp))
        for i in tmp:
            self.ui.tableWidget.setColumnWidth(i,newsize)
    return False

Upvotes: 0

Adan RH
Adan RH

Reputation: 65

I found the way to do it, first i need to set the width of each column to fit the QTableView size, and then i stretch the last section, so now each column can be resized.

  for(int c = 0;c<=4;c++){
    ui->tableView->horizontalHeader()->resizeSection(c, 150);

    }

    ui->tableView->horizontalHeader()->setStretchLastSection(true);

Thanks

Upvotes: 2

Related Questions