5

I see how to detect click in a QTableWidget cell by watching the cellClicked(int row, int column) signal (code below).

I would like to do the same for the cells of the horizontal header and get the text of the clicked header cell. How do I do that?

// mainwindow.h
class MainWindow : public QMainWindow {
    Q_OBJECT
    QWidget widget;
    QVBoxLayout vLayout {&widget};
    QStringList headers {"asdca", "asdcad", "asdcadca"};
    QTableWidget table {5, headers.size()};
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow() {}
};

// mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    setCentralWidget(&widget);
    vLayout.addWidget(&table);
    table.setHorizontalHeaderLabels(headers);
    connect(&table, &QTableWidget::clicked, []{
       qDebug() << "click!!" ;
    });
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
KcFnMi
  • 5,516
  • 10
  • 62
  • 136

2 Answers2

7
auto header = table->horizontalHeader();
connect(header, &QHeaderView::sectionClicked, [this](int logicalIndex){
    QString text = table.horizontalHeaderItem(logicalIndex)->text();
   qDebug() << logicalIndex << text;
});
Chnossos
  • 9,971
  • 4
  • 28
  • 40
KcFnMi
  • 5,516
  • 10
  • 62
  • 136
4

You can get QHeaderView for you QTableWidgetwith method horizontalHeader. QHeaderView have signal sectionClicked. You can use it to determine text of the header item.

Kirill Chernikov
  • 1,387
  • 8
  • 21