Detect click and get text of QTableWidget header, how?
Asked Answered
M

2

6

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!!" ;
    });
}
Mononuclear answered 14/7, 2016 at 11:54 Comment(0)
M
11
auto header = table->horizontalHeader();
connect(header, &QHeaderView::sectionClicked, [this](int logicalIndex){
    QString text = table.horizontalHeaderItem(logicalIndex)->text();
   qDebug() << logicalIndex << text;
});
Mononuclear answered 14/7, 2016 at 12:38 Comment(0)
J
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.

Ja answered 14/7, 2016 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.