Qt setHorizontalHeaderLabels for tableWidget

THE DOCTOR picture THE DOCTOR · May 30, 2012 · Viewed 11.8k times · Source

How would I go about using the setHorizontalHeaderLabels property of my tableWidget to specify names for my columns as opposed to numbers? I want to keep my rows as numbers, but change my columns to names I have collected into a QList.

Right now, I have the values for row and column set as integers. When I attempt to use setHorizontalHeaderLabels, it seems that the integer values for columns override the column names that I'm attempting to specify and I don't know how to fix it.

This is how I am setting the values currently which just involves integer values for my rows and columns:

    QList< QStringList > columnHeaderList; 

    //--- create the horizontal (column) headers
    QStringList horzHeaders;
    ui->tableWidget_inputPreview->setHorizontalHeaderLabels( horzHeaders );
    horzHeaders << "test1" << "test2" << "test3"; 

    ui->tableWidget_inputPreview->setRowCount( rowList.size() - 1 );
    ui->tableWidget_inputPreview->setColumnCount( columnHeaderList[0].size() );

for ( int row = 0; row < rowList.size(); ++row ) {
    for ( int column = 0; column < rowList[row].size(); ++column ) {
        ui->tableWidget_inputPreview->setItem(row, column, new QTableWidgetItem(rowList[row][column]));
    }
}

I need some guidance on how to properly take the values from my QList and set the columns as those values for my tableWidget. The columns that appear in my tableWidget are 1, 2, 3, 4, 5, 6, 7 which comes from the number of items being passed to it in setColumnCount instead of test1, test2, test3.

Answer

cgmb picture cgmb · May 30, 2012

In your example, you set setHorizontalHeaderLabels to an empty list. Be sure to fill it before setting the headers. Also, set the headers after setting the column count.

This is the sort of order you want:

//--- create the horizontal (column) headers
QStringList horzHeaders;
horzHeaders << "test1" << "test2" << "test3";
ui->tableWidget_inputPreview->setRowCount( rowList.size() - 1 );
ui->tableWidget_inputPreview->setColumnCount( columnHeaderList[0].size() );
ui->tableWidget_inputPreview->setHorizontalHeaderLabels( horzHeaders );