tags:

views:

193

answers:

1

I want the size of the QTableView to be the same as the table it contains (and fixed) so that it does not have a scrollbar

+1  A: 

What you could do is calculate your tableview columns widths according to the data they have (or you can just call resizeColumnToContents for each column to size it to its content). Then change the tableview width to be equal or more then total width of columns + vertical header if shown. You would also need to track model changes and adjust your tableview width + if horizontal header is shown you can track columns resize events and adjust them again. Below is some sample code for this:

initialization:

// add 3 columns to the tableview control
tableModel->insertColumn(0, QModelIndex());
tableModel->insertColumn(1, QModelIndex());
tableModel->insertColumn(2, QModelIndex());
...
// switch off horizonatal scrollbar; though this is not really needed here  
ui->tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);    
// adjust size; see code below
adjustTableSize();
// connect to the horizontal header resize event (non needed if header is not shown)
connect(ui->tableView->horizontalHeader(),SIGNAL(sectionResized(int,int,int)), this,
              SLOT(updateSectionWidth(int,int,int)));
// connect to the model's datachange event
connect(ui->tableView->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
                this, SLOT(dataChanged(QModelIndex,QModelIndex)));

adjust tableview size:

void MainWindow::adjustTableSize()
{
    ui->tableView->resizeColumnToContents(0);
    ui->tableView->resizeColumnToContents(1);
    ui->tableView->resizeColumnToContents(2);

    QRect rect = ui->tableView->geometry();
    rect.setWidth(2 + ui->tableView->verticalHeader()->width() +
            ui->tableView->columnWidth(0) + ui->tableView->columnWidth(1) + ui->tableView->columnWidth(2));
    ui->tableView->setGeometry(rect);
}

process model change

void MainWindow::dataChanged(const QModelIndex &topLeft, const QModelIndex   &bottomRight)
{
    adjustTableSize();
}

process horizontal header resize

void MainWindow::updateSectionWidth(int logicalIndex, int, int newSize)
{
    adjustTableSize();
}

hope this helps, regards

serge_gubenko
thx but I was already able to do it. THe only problem here is you need to take into account the border size. Also there is something wrong with the width() and height() methods of the vertical healder. The width method gives a value of 0 an the height gave me something like 259, which was way too big.
yan bellavance
the horizontal header goves good values though.
yan bellavance