【问题标题】:checkbox on QtableWidget's headerQtableWidget 标题中的复选框
【发布时间】:2017-07-16 19:36:57
【问题描述】:

如何在 QTableWidget Header 上设置复选框。如何在 QHeaderView 中添加全选复选框.. 它不显示复选框..

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

【问题讨论】:

    标签: c++ qt qt5.6


    【解决方案1】:

    Here, at Qt Wiki, 它说没有捷径,你必须自己继承 headerView。

    这是该 wiki 答案的摘要:

    "目前还没有API可以在header中插入widget,但是你可以自己绘制checkbox以便将它插入到header中。

    你可以做的是继承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();
    }
    

    【讨论】:

    • 没有其他方法可以从表格视图中调用标题中的复选框吗?
    • 我们必须绘制我们自己设计的复选框,并且必须从表格视图的标题中调用。谢谢,我会尝试这种方法来实现复选框。
    【解决方案2】:

    代替上述解决方案,您可以简单地将按钮放在全选复选框的位置,并为“全选”提供一个名称按钮。

    因此,如果您按下全选按钮,则它称为按钮并在您使用按钮时转到(此处全选)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 2014-06-20
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      相关资源
      最近更新 更多