KcFnMi
KcFnMi

Reputation: 6171

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

Upvotes: 6

Views: 9139

Answers (2)

KcFnMi
KcFnMi

Reputation: 6171

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

Upvotes: 11

Kirill Chernikov
Kirill Chernikov

Reputation: 1420

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

Upvotes: 4

Related Questions