How to insert string inside a cell in QTableWidget



  • Possible duplicate: http://stackoverflow.com/questions/10453343/filling-some-qtablewidgetitems-with-qstring-from-file

    How to insert rows at run time in a QTableWidget?
    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(&#41;;
    

    }@


  • Moderators

    You iterate i and j up to rowCount and columnCount but you don't have any rows or columns.
    Either add them in the designer or call setRowCount and setColumnCount at runtime before you start to add cells.



  • Thank u @Chris, i added those lines and could insert QString line in every cell.
    [quote author="Chris Kawa" date="1401117578"]You iterate i and j up to rowCount and columnCount but you don't have any rows or columns.
    Either add them in the designer or call setRowCount and setColumnCount at runtime before you start to add cells.[/quote]


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.