Qt setHorizontalHeaderLabels for tableWidget

13,292

Solution 1

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 );

Solution 2

Also realize that calling ui->tableWidget_inputPreview->clear() will remove the labels.

Consider ui->tableWidget_inputPreview->clearContents() to keep the labels.

Share:
13,292
THE DOCTOR
Author by

THE DOCTOR

I am a Time-Lord from the planet Gallifrey and the last remaining survivor of my race. I have regenerated several times now as follows: Database Developer -&gt; QA Engineer -&gt; Software Engineer -&gt; Network/Systems Engineer -&gt; Director of IT &amp; Network Engineering.

Updated on June 30, 2022

Comments

  • THE DOCTOR
    THE DOCTOR almost 2 years

    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.