DeeRose
DeeRose

Reputation: 21

Add a String as an Item to a tableWidget in QT/Python

I have an array with strings and I want to add each string in a different row and the same column of a tableWidget.

I'm using the function setItem to change the desired field, but I get the error QTableWidget.setItem(int, int, QTableWidgetItem): argument 3 has unexpected type 'str'. I've searched a little and I think I have to use the function QTableWidgetItem (here) to convert the string into a tableWidgetItem, however, I have no idea how to use that function, and what 'type' means (the integer value).

An (concrete) example how to use that function to convert a string into a tableWidgetItem would be very helpful.

So far my code looks like this:

pc = 2
i = 0
while i <= pc:
    self.tableWidget.insertRow(i)
    self.tableWidget.setItem(i, 0, parameter[i])
    i += 1

It would also be helpful if someone points out if there's a better way to add a string to a tableWidget than setItem.

Upvotes: 2

Views: 9329

Answers (2)

Chenna V
Chenna V

Reputation: 10473

You get the error because setItem takes in QTableWidgetItem* as input for the third argument. Try this

pc = 2
self.tableWidget.setRowCount(pc)
i = 0
while i <= pc:
    self.tableWidget.setItem(i, 0, QtGui.QTableWidgetItem(parameter[i]))
    i += 1

Upvotes: 0

Stephen Terry
Stephen Terry

Reputation: 6279

The QTableWidgetItem constructor accepts a string as an argument. In your case, you just need to change your fifth line to (assuming parameter is a list of strings)

self.tableWidget.setItem(i, 0, QtGui.QTableWidgetItem(parameter[i]))

Upvotes: 6

Related Questions