Nothing is shown because the argument item
of QTableWidget.setItem
you spend just that, nothing. When doing:
QTableWidgetItem(_id).setTextAlignment(QtCore.Qt.AlignHCenter)
what you do is the following:
You create an object QTableWidgetItem
with QTableWidgetItem(_id)
.
Slaps to the setTextAlignment
of the newly created object, which correctly maps the alignment and return. This method returns None
and it is that return that is passed to QTableWidget.setItem
, not an instance of QTableWidgetItem
.
Therefore, what you do is basically:
self.tabla.setItem(self.tabla.rowCount() - 1, 0, None)
The solution is simple, instantiate the object and assign it to a variable to keep a reference to it, then use that variable to call its method setTextAlignment
and finally pass it to QTableWidget.setItem
:
self.tabla.insertRow(self.tabla.rowCount())
item = QTableWidgetItem(_id)
item.setTextAlignment(QtCore.Qt.AlignHCenter)
self.tabla.setItem(self.tabla.rowCount() - 1, 0, item)
A reproducible example:
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QTableWidget, QTableWidgetItem, QVBoxLayout
from PyQt5 import QtCore
class Example(QDialog):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
self.tableWidget = QTableWidget()
self.layout.addWidget(self.tableWidget)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
for i in range(4):
for j in range(2):
item = QTableWidgetItem("Item {}-{}".format(i, j))
item.setTextAlignment(QtCore.Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())