How to align the text to center of cells in a QTableWidget

This line of code:

item = QTableWidgetItem(scraped_age).setTextAlignment(Qt.AlignHCenter)

will not work properly, because it throws away the item it creates before assigning it to the variable. The variable will in fact be set to None, which is the return value of setTextAlignment(). Instead, you must do this:

item = QTableWidgetItem(scraped_age) # create the item
item.setTextAlignment(Qt.AlignHCenter) # change the alignment

Leave a Comment