QStandardItemModel inside Qtableview

倖福魔咒の 提交于 2019-12-11 08:49:12

问题


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")));


回答1:


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

or

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



回答2:


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();



回答3:


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.



来源:https://stackoverflow.com/questions/16931569/qstandarditemmodel-inside-qtableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!