Search code examples
c++qtqt5qtablewidgetqtablewidgetitem

Detect click and get text of QTableWidget header, how?


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

Solution

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