2
votes

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!!" ;
    });
}
2

2 Answers

3
votes
auto header = table->horizontalHeader();
connect(header, &QHeaderView::sectionClicked, [this](int logicalIndex){
    QString text = table.horizontalHeaderItem(logicalIndex)->text();
   qDebug() << logicalIndex << text;
});
2
votes

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