Pergunta

I am using QStandardItemModel inside QTableView. Here i have two button & Qtableview inside my mainwindow. I need only 4 columns inside this. And rows will vary. The two Buttons will be used to add/delete a row (test case).

  1. setHorizontalHeaderItem is not showing all the text(means all text is not visible). Example if i put 'Text for the Employee Name' it is not fully visible ?
  2. How to make QStandardItemModel occupy full QTableview (width). At present it is showing at top left corner ?

How to achieve it?

Code :

model= new QStandardItemModel(4, 4);

    for (int row = 0; row < 4; ++row) {
        for (int column = 0; column < 4; ++column) {
            QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
            model->setItem(row, column, item);
        }
    }

    model->setHorizontalHeaderItem(0, new QStandardItem(tr("Time")));
    model->setHorizontalHeaderItem(1, new QStandardItem(tr("Text for the Employee Name")));
    model->setHorizontalHeaderItem(2, new QStandardItem(tr("Text for the Employee Address")));
    model->setHorizontalHeaderItem(3, new QStandardItem(tr("Text for the Employee Date of Birth")));

    model->setVerticalHeaderItem(0, new QStandardItem(tr("Test-Case-----1")));

enter image description here

Foi útil?

Solução

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

or

tableView->horizontalHeader()->setResizeMode(QHeaderView::Stretch);

Outras dicas

As the question is already accepted for the answer, my answer may help someone, as the above accepted answer didn't help me.

QStandardItemModel *model = new QStandardItemModel(2,3,this);
//----------
ui->tableView->setModel(model);
ui->tableView->resizeColumnsToContents();

I know the answer comes a bit late, but I was just needing to do the same, and figured out a different solution.

To achieve your goal in Qt 4, you need to adjust the settings of the header of your QTableView. To do so, first retrieve the header:

QHeaderView *header = ui->tableView->horizontalHeader();

Next, adjust the resize mode of the individual columns by calling QHeaderView::setResizeMode (the second flavor, which accepts logicalIndex):

header->setResizeMode(0, QHeaderView::ResizeToContents);
header->setResizeMode(1, QHeaderView::ResizeToContents);
header->setResizeMode(2, QHeaderView::ResizeToContents);
header->setResizeMode(3, QHeaderView::Stretch);

In the above example, I chose to stretch column 3, but you may choose any of the columns to be in "stretch" mode.

In Qt 5, the call you want is QHeaderView::setSectionResizeMode().

Hope this helps you or anybody else seeking a solution to this problem.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top