简体   繁体   中英

QtableWidget does not show data

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;
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM