QTableView shows 1d data in exactly one row/column. How to show it two-dimensionally?

925 views Asked by At

Say I have a one-dimensional QStandardItemModel and a QTableView instance:

QStandardItemModel model;
for (int i = 1; i < 10; ++i) {
    QStandardItem *item = new QStandardItem(QString::number(i));
    model.appendRow(item);
}

QTableView tableView;
tableView.setModel(&model);
tableView.show();

This shows the data in the first column, but I want to show it in a two-dimensional way like this:

1 2 3
4 5 6
7 8 9

Additionally the user should be able to select the data, which means that a custom QStyledItemDelegate probably isn't the way to go to implement this.

So one needs to create a custom QAbstractItemView, where the documentation is unfortunately a bit lacking in my opinion. Help?

1

There are 1 answers

1
Jablonski On

First of all, if you want show data as 2d array, you shoul write another loop. For example this:

int counter = 0;
QStandardItemModel *model = new QStandardItemModel(this);
for (int i = 0; i < 3; ++i)
    for (int j = 0; j < 3; ++j)
    {
        counter++;
        QStandardItem *item = new QStandardItem(QString::number(counter));
        model->setItem(i,j,item);
    }

ui->tableView->setModel(model);

On my computer this works exactly as you want.

Secondly. User can do different actions with cells. QTableView have a few very good signals. With this signal, we can communicate with cells. I write one more code snippet.

int counter = 0;
QStandardItemModel *model = new QStandardItemModel(this);
for (int i = 0; i < 3; ++i)
    for (int j = 0; j < 3; ++j)
    {
        counter++;
        QStandardItem *item = new QStandardItem(QString::number(counter));
        model->setItem(i,j,item);
    }
connect(ui->tableView,SIGNAL(clicked(QModelIndex)),this,SLOT(clickedIndex(QModelIndex )));
ui->tableView->setModel(model);
//...
void MainWindow::clickedIndex(QModelIndex index)
{
    if(index.isValid())
    {
        ui->tableView->model()->setData(index,QString("you press %1 , %2 cell").arg(index.row()).arg(index.column()));
    }
}

In this example, when user clicked on some cell, text in the cell tell him number of this cell. I hope,it helps.