Important: Please read the Qt Code of Conduct -

How to Add column names to QTableWidget present in QDialog?

  • Hi,

    I am unable to add new column names to QTableWidget. I am using setHorizontalHeaderLabels function still unable to add names. Here is the snippet:

    def Dialog(self):
         table = self.MyTable(Big21,3,1)
         # this prevents the garbage collector
                     # from deleting the new table
         self.table = table
    def MyTable(self,data,*args):
         QTableWidget.__init__(self) = data
         columns = ['A','B']
         tableWidget = QTableWidget()
         for i in range (0,len(data)):
             for j in range (0,len(data.columns)):
                 item1 = str(data.iloc[i,j])
                 tableWidget.setItem(i, j,  QTableWidgetItem(item1))
         return tableWidget

  • Lifetime Qt Champion

    you have to increase col count
    to allow for one more :)

  • @mrjj Hi,
    Actually the code works if I move the line tableWidget.setHorizontalHeaderLabels(columns) after assigning columncount.

  • Lifetime Qt Champion

    Hi :)
    Well setHorizontalHeaderLabels also uses the col count and it must be correct.

  • You can set header contents for existing columns via the "setHeaderData()" of your table's model, eg.:

    p_table->model()->setHeaderData( column_index, Qt::Horizontal, "Hello", Qt::DisplayRole );

Log in to reply