1

I have created a table in PyQt5 and populated it similar to how it's done in this post. I want to center align all the cells but when I try to align each cell my QTableWidgetItem becomes None.

According to the docs setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter) should work. See here too

Here is a working example where self.db_table is the QTableWidget.

for row in rows:
    inx = rows.index(row)
    self.db_table.insertRow(inx)
    self.db_table.setItem(inx, 0, QTableWidgetItem(str(row[0])))
    self.db_table.setItem(inx, 1, QTableWidgetItem(str(row[1])))
    self.db_table.setItem(inx, 2, QTableWidgetItem(str(row[2])))
    self.db_table.setItem(inx, 3, QTableWidgetItem(str(row[3])))
    self.db_table.setItem(inx, 4, QTableWidgetItem(str(row[4])))

And when I add the setTextAlignment() it makes all the QTableWidgetItems None:

for row in rows:
    inx = rows.index(row)
    self.db_table.insertRow(inx)
    self.db_table.setItem(inx, 0, QTableWidgetItem(str(row[0])).setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter))
    self.db_table.setItem(inx, 1, QTableWidgetItem(str(row[1])).setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter))
    self.db_table.setItem(inx, 2, QTableWidgetItem(str(row[2])).setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter))
    self.db_table.setItem(inx, 3, QTableWidgetItem(str(row[3])).setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter))
    self.db_table.setItem(inx, 4, QTableWidgetItem(str(row[4])).setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter))

Is there any reason why this isnt working?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
N.Zano
  • 15
  • 1
  • 4

1 Answers1

5

the setTextAlignment() method does not return any parameters and that equals None, and then you are passing None to setItem, what you must do is create the item as item = QTableWidgetItem({}) and then use item.setTextAlignment({}) and at the end add it self.db_table.setItem(inx, 0, item) for each element, a reduced form is the following:

for row in rows:
    inx = rows.index(row)
    self.db_table.insertRow(inx)
    for i, v in zip(range(5), row):
        item = QTableWidgetItem(str(v))
        item.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter)
        self.db_table.setItem(inx, i, item)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241