QStandardItemModel inside Qtableview
Asked Answered
T

3

1

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

Tailrace answered 5/6, 2013 at 4:27 Comment(0)
H
4
tableView->horizontalHeader()->setStretchLastSection(true);

or

tableView->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
Hiltonhilum answered 5/6, 2013 at 6:4 Comment(0)
D
1

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();
Disincline answered 10/4, 2015 at 4:27 Comment(1)
this answer did not fulfill the questionTryst
U
0

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.

Unconcern answered 5/2, 2018 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.