Align text of items in a QTableWidget

1

I am trying to center the texts of an item of QTableWidget for which I occupy the following:

self.tabla.insertRow(self.tabla.rowCount())
self.tabla.setItem(self.tabla.rowCount()-1,0,QTableWidgetItem(_id).setTextAlignment(QtCore.Qt.AlignHCenter))

but it does not center the text, on the contrary, when including the line .setTextAlignment(QtCore.Qt.AlignHCenter) the text is not even shown.

    
asked by Mystic_Force 07.08.2018 в 00:24
source

1 answer

3

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_())
    
        
    answered by 07.08.2018 / 00:55
    source