3

I have a class that creates random data which I would like to show in a tableview on the main window.

I added via Designer a table view to the main window and called it tblData. I suspect the problem is related to this because when I call the constructor the ui file with some implementation is already there.

I have taken the "Detailed Description" section from http://qt-project.org/doc/qt-5/qtablewidget.html as guidance....

However, the table remains empty. I do not see why... Thank you very much.

include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStringList headers;
    headers << "Datapoints";

    Dataset *myData;
    myData = new Dataset();
    myData->createRandomData(10);   // create a ten element vector

    QVector<int> data;
    data = myData->getDataVector(); // data vector created in class Dataset
    qDebug() << data;

    int i;
    for (i = 0 ; i < data.size() ; i++){
        QString datapoint;
        datapoint = QString::number(data[i]);
        QTableWidgetItem * newItem = new QTableWidgetItem(datapoint);

        ui->tblData->setItem(i, 0, newItem); // works not


        qDebug() << datapoint;  // works
    }


}

MainWindow::~MainWindow()
{
    delete ui;
}
RogerWilco77
  • 319
  • 1
  • 3
  • 13
  • 2
    What if you call `ui->tblData->setRowCount(data.size()); ui->tblData->setColumnCount(1);` before your `for` loop? – vahancho Sep 27 '14 at 14:23
  • Magic! This works. Would you be so kind to add it as an answer so I can mark it as solved? But honestly: I do not understand why initializing each element as QTableWidget was not sufficient... – RogerWilco77 Sep 27 '14 at 20:14

1 Answers1

12

I think you have to define your table's dimensions before starting to populate it with the data, i.e.

ui->tblData->setRowCount(data.size());
ui->tblData->setColumnCount(1);

The reason is that by default the initial row and column count of the table is 0, so the newly added items are not visible.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • I totally forgot about this :) You are quite right, +1 – Jablonski Sep 28 '14 at 08:21
  • ok, thank you very much. originally I started out with the book by Jürgen Wolf "Qt4 Gui-Entwicklung mit c++" (the one for 4.5) and there I did not realize that on page 271 he defined the size of the table in the beginning. His table size does not change, so he can define the size at compile time. Thanks! – RogerWilco77 Sep 28 '14 at 10:43
  • OMG you made my day … +1 – TheEagle Oct 25 '21 at 23:48