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)
         table.show()
         # this prevents the garbage collector
                     # from deleting the new table
         self.table = table
             
    def MyTable(self,data,*args):
         QTableWidget.__init__(self)
         self.data = data
         columns = ['A','B']
         tableWidget = QTableWidget()
         tableWidget.setHorizontalHeaderLabels(columns)
         tableWidget.setRowCount(len(data))
         tableWidget.setColumnCount(len(data.columns))
         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

  • Qt Champions 2017

    HI
    you have to increase col count
    tableWidget.setColumnCount
    to allow for one more :)

    https://wiki.qt.io/How_to_Use_QTableWidget



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


  • Qt Champions 2017

    @Piyush
    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.