user2775042
user2775042

Reputation: 509

How to put data into a QTable Widget Item from a file?

I have Qtable and file called input.txt

I am trying to display the data on the Qtable widget by reading from the input.txt.

the table has 9 rows and 9 columns. I tried making a QTable widget item and used a for loop to put data into it. but couldnt get it work.

Here is the code i have tried

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

QTableWidgetItem *item = new QTableWidgetItem;
item->setText(QString("1"));

bool check = false;

while(!check){

    for (int row = 0; row < 9; ++row) {
        for (int col = 0; col < 9; ++col) {

        }

        item = new QTableWidgetItem();
        item->setText((std::to_string(n)));
        ui->tableWidget->setItem(row,col,item);
        n++;

        if(row ==8 , col ==8){
            check = true;
    }

}

}

This was just a demo to check if i can add numbers to each cell.

Upvotes: 1

Views: 2412

Answers (1)

b00dle
b00dle

Reputation: 1528

There are a couple things that you have to change. First of, set the row count and column count for your table, using

QTableWidget::setColumnCount(int columnCount)
QTableWidget::setRowCount(int rowCount)

Then, it is always safer to use set sizes for your iteration, to make sure you don't go 'out of bounds'. Get them by:

int QTableWidget::columnCount()
int QTableWidget::rowCount()

Finally to construct QTableWidgetItem you have to use QString instead of std::string (see docs).

Here is a minimum example for you:

QTableWidget* table_widget = new QTableWidget(this);

table_widget->setColumnCount(9);
table_widget->setRowCount(9);

for(int r = 0; r < table_widget->rowCount(); ++r) {
    for(int c = 0; c < table_widget->columnCount(); ++c) {
        table_widget->setItem(r, c, new QTableWidgetItem(QString::number(r+c)));
    }
}

You might want to check out these tutorials. They are an awesome resource to get familiar with a lot of basic functionality in no time. You'll find answers about how to parse files in Qt in there, too.

Happy coding!

Upvotes: 1

Related Questions