QtableWidget 标题上的复选框

checkbox on QtableWidget's header

本文关键字:复选框 标题 QtableWidget      更新时间:2023-10-16

如何在qtableWidget标头上设置复选框。如何在qheaderview中添加选择所有复选框。它不显示复选框..

 QTableWidget* table = new QTableWidget();
 QTableWidgetItem *pItem = new QTableWidgetItem("All");
 pItem->setCheckState(Qt::Unchecked);
 table->setHorizontalHeaderItem(0, pItem);

在这里,在qt wiki上,它说没有快捷方式,您必须自己为标头表。

这是Wiki答案的摘要:

"当前没有API可以在标题中插入小部件,但是您可以自己绘制复选框以将其插入标题。

您可以做的是子类qheaderview,重新进化paintsection(),然后在您想要拥有此复选框的部分中使用pe_indicatorCheckbox调用drawprimitive()。

您还需要重新完成Mousepressevent()才能检测到何时单击复选框,以绘制检查和未检查的状态。

下面的示例说明了如何完成:

#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();
}

而不是上述解决方案,您只需按下按钮以取代所有复选框,然后给出一个名称按钮以"选择全部"。

因此,如果按下所有按钮,则将其称为按钮,然后随时使用按钮(此处选择全部)。