QTableWidget set header labels

Viewed 722

I use a QTableWidget, not QTableView. No model added. I just work with QTableWidgetItem. However, Everything is working fine expect the QTableWidget Headers. I was not successful into adding header names to to the columns header.

I tried as sample:

    listWidget = new QTableWidget(); //listWidget is a QTablewWidget...old code, sorry.
    QStringList headers;
    headers << "Name" << "Date" << "Undso";
    listWidget->setHorizontalHeaderLabels(headers);

    listWidget->setColumnCount(3);
    listWidget->setColumnWidth(0, 250);
    listWidget->setColumnWidth(1, 100);

    listWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    listWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
    listWidget->horizontalHeader()->setStretchLastSection(true);
    listWidget->verticalHeader()->hide();
    listWidget->setShowGrid(false);

I also tried some other ways found here on stackoverflow but no success. All the times the headers show just numbers.

Any hint what I do wrong or miss?

2 Answers

First you have to set the number of columns and then the header labels:

listWidget->setColumnCount(3);
listWidget->setHorizontalHeaderLabels(headers);

I know this was not the problem in this case, but I had the same problem, and the above answer did not fix the problem for me. I had to additionally remove a

listWidget->clear();

I had after setHorizontalHeaderLabels.

Related