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?
Asked
Active
Viewed 6,993 times
4
-
I need some functions I think but I don't know which functions should I use? – Enes Altuncu Sep 10 '15 at 16:12
-
did you tried to google something? like "qtablewidget add row"? have you read some of the results? – gengisdave Sep 10 '15 at 16:22
-
Yes, but I have a problem. I need to add text to the cell, not item. In the results in google, it shows the method with item. – Enes Altuncu Sep 10 '15 at 16:44
-
yes, you can't add text directly to a `QTableWidget` cell, you have to do through a `QTableWidgetItem` (one cell at a time) – gengisdave Sep 10 '15 at 16:47
-
I'm getting the filenames from a directory and add them to the tablewidget. So, how can I do that by using QTableWidgetItem? – Enes Altuncu Sep 10 '15 at 16:51
1 Answers
7
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"));

gengisdave
- 1,969
- 5
- 21
- 22