3

How to set checkbox on QTableWidget Header. How To Add Select All Checkbox in QHeaderView.. It does not displays a checkbox..

 QTableWidget* table = new QTableWidget();
 QTableWidgetItem *pItem = new QTableWidgetItem("All");
 pItem->setCheckState(Qt::Unchecked);
 table->setHorizontalHeaderItem(0, pItem);
Senthil Kumar
  • 562
  • 1
  • 6
  • 14

2 Answers2

0

Here, at Qt Wiki, it says there is no shortcut for it and you have to subclass headerView yourself.

Here is a summary of that wiki answer:

"Currently there is no API to insert widgets in the header, but you can paint the checkbox yourself in order to insert it into the header.

What you could do is to subclass QHeaderView, reimplement paintSection() and then call drawPrimitive() with PE_IndicatorCheckBox in the section where you want to have this checkbox.

You would also need to reimplement the mousePressEvent() to detect when the checkbox is clicked, in order to paint the checked and unchecked states.

The example below illustrates how this can be done:

#include <QtGui>

class MyHeader : public QHeaderView
{
public:
  MyHeader(Qt::Orientation orientation, QWidget * parent = 0) : QHeaderView(orientation, parent)
  {}

protected:
  void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
  {
    painter->save();
    QHeaderView::paintSection(painter, rect, logicalIndex);  
    painter->restore();
    if (logicalIndex == 0)
    {
      QStyleOptionButton option;
      option.rect = QRect(10,10,10,10);
      if (isOn)
        option.state = QStyle::State_On;
      else
        option.state = QStyle::State_Off;
      this->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter);
    }

  }
  void mousePressEvent(QMouseEvent *event)
  {
    if (isOn)
      isOn = false;
    else 
      isOn = true;
    this->update();
    QHeaderView::mousePressEvent(event);
  }
private:
  bool isOn;
};


int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QTableWidget table;
  table.setRowCount(4);
  table.setColumnCount(3);

  MyHeader *myHeader = new MyHeader(Qt::Horizontal, &table);
  table.setHorizontalHeader(myHeader);  
  table.show();
  return app.exec();
}
t.m.
  • 1,430
  • 16
  • 29
  • There is no alternative method for calling the checkbox within the header from table view? – Senthil Kumar Feb 27 '17 at 09:26
  • We have to paint the checkbox our self to design and have to call from header from table view.. Thanks, I will try this method for implementing checkbox. – Senthil Kumar Feb 27 '17 at 09:28
0

Instead of above solution, You can simply put Push button in place of select all check box and give a name push button to "select all".

So If you press select all button then it called push button and go to whenever you go with push button(Here select all).

Harnish Shah
  • 442
  • 3
  • 14