Qt how to insert string inside a cell in QTableWidget

cappy0704 picture cappy0704 · May 26, 2014 · Viewed 13.7k times · Source

Possible duplicate: Filling some QTableWidgetItems with QString from file

  1. How to insert rows at run time in a QTableWidget?
  2. How to insert hard coded strings in the cells of this QTableWidget?

Here's what I tried before getting stuck... I have inserted the QTableWidget using the Qt designer.

the code: mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

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

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

    /*add stuff inside the table view*/
    QString line = "hello";
    for(int i=0; i<ui->tableWidget->rowCount(); i++)
    { 
        for(int j=0; j<ui->tableWidget->columnCount(); j++)
        {
            QTableWidgetItem *pCell = ui->tableWidget->item(i, j);
            if(!pCell)
            {
                pCell = new QTableWidgetItem;
                ui->tableWidget->setItem(i, j, pCell);
            }
            if(!line.isEmpty())
                pCell->setText(line);
        }
    }
#if 0
    const int rowAdder = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(rowAdder);
    QString str = "hello";
    ui->tableWidget->
#endif
}

MainWindow::~MainWindow()
{
    delete ui;
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Answer

cappy0704 picture cappy0704 · May 27, 2014

Thank you @Laszlo Papp, I removed the if(!line.isEmpty()) . Also, I found that I had missed creating rows and columns, until now i had only created 3 columns using the designer. I added two statements for adding rows and columns. And it worked. Here is the code:-

mainwindow.cpp

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    /*add rows and columns*/
    ui->tableWidget->setRowCount(10);
    ui->tableWidget->setColumnCount(3);

    /*add stuff inside the table view*/
    QString line = "hello";
    for(int i=0; i<ui->tableWidget->rowCount(); i++)
    { 
        for(int j=0; j<ui->tableWidget->columnCount(); j++)
        {
            QTableWidgetItem *pCell = ui->tableWidget->item(i, j);
            if(!pCell)
            {
                pCell = new QTableWidgetItem;
                ui->tableWidget->setItem(i, j, pCell);
            }
            pCell->setText(line);
        }
    }
}

This is the expected and obtained output.