Enes Altuncu
Enes Altuncu

Reputation: 439

How to add text to a cell of a tablewidget

I have a tablewidget in my application. It has 2 columns including filename and filepath. I want to add text to this tablewidget with a pushbutton and use this text to do some operation. How to do this?

Upvotes: 4

Views: 8137

Answers (1)

gengisdave
gengisdave

Reputation: 2050

You can't add text (QString) directly to a QTableWidget, you must first create a QTableWidgetItem and then insert it into the desired cell. Example:

// create a new qtablewidget
QTableWidget tablewidget;

// our tablewidget has 2 columns
tablewidget.setColumnCount(2);

// we insert a row at position 0 because the tablewidget is still empty
tablewidget.insertRow(0);

// we add the items to the row we added
tablewidget.setItem(0, 0, new QTableWidgetItem("first row, first column"));
tablewidget.setItem(0, 1, new QTableWidgetItem("first row, second column"));

if you have more columns, the way is the same

if you want to add more rows (and this is good even with the first), you can use a generic

tablewidget.insertRow(tablewidget.rowCount());

which always add a new row at the end of the table (append);

more difficult: this should explain how insertRow() is different (and powerful) than a non-existent appendRow()

QTableWidget tablewidget;
tablewidget.setColumnCount(2);

// we insert a row at position 0 because the tablewidget is still empty
tablewidget.insertRow(tablewidget.rowCount());

tablewidget.setItem(0, 0, new QTableWidgetItem("first row, first column"));
tablewidget.setItem(0, 1, new QTableWidgetItem("first row, second column"));

// "append" new row at the bottom with rowCount()
tablewidget.insertRow(tablewidget.rowCount());
tablewidget.setItem(1, 0, new QTableWidgetItem("second row, first column"));
tablewidget.setItem(1, 1, new QTableWidgetItem("second row, second column"));

// we insert a "new" second row pushing the old row down
tablewidget.insertRow(1);
tablewidget.setItem(1, 0, new QTableWidgetItem("this push the"));
tablewidget.setItem(1, 1, new QTableWidgetItem("second row down"));

Upvotes: 7

Related Questions