Checkbox in a header cell in QTableView

后端 未结 3 792
礼貌的吻别
礼貌的吻别 2020-12-16 20:57

I want to have a simple column header with a checkbox that selects/ deselects all rows in a QTableView. Clicking the check box in the header causes either to select or desel

3条回答
  •  时光说笑
    2020-12-16 21:05

    Here is a bit modified/fixed (checkbox was displayed as disabled and redrawing didn't work) code from the link in the accepted answer.

    .h

    class CheckBoxHeader : public QHeaderView
    {
        Q_OBJECT
    
    public:
        CheckBoxHeader(Qt::Orientation orientation, QWidget* parent = 0);
    
        bool isChecked() const { return isChecked_; }
        void setIsChecked(bool val);
    
    signals:
        void checkBoxClicked(bool state);
    
    protected:
        void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const;
    
        void mousePressEvent(QMouseEvent* event);
    
    private:
        bool isChecked_;
    
        void redrawCheckBox();
    };
    

    .cpp

    #include "CheckBoxHeader.h"
    
    CheckBoxHeader::CheckBoxHeader(Qt::Orientation orientation, QWidget* parent /*= 0*/)
        : QHeaderView(orientation, parent)
    {
        isChecked_ = true;
    }
    
    void CheckBoxHeader::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(1,3,20,20);
    
            option.state = QStyle::State_Enabled | QStyle::State_Active;
    
            if (isChecked_)
                option.state |= QStyle::State_On;
            else
                option.state |= QStyle::State_Off;
            option.state |= QStyle::State_Off;
    
            style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter);
        }
    }
    
    void CheckBoxHeader::mousePressEvent(QMouseEvent* event)
    {
        setIsChecked(!isChecked());
    
        emit checkBoxClicked(isChecked());
    }
    
    void CheckBoxHeader::redrawCheckBox()
    {
        viewport()->update();
    }
    
    void CheckBoxHeader::setIsChecked(bool val)
    {
        if (isChecked_ != val)
        {
            isChecked_ = val;
    
            redrawCheckBox();
        }
    }
    

    usage

    CheckBoxHeader* header = new CheckBoxHeader(Qt::Horizontal, &table);
    table.setHorizontalHeader(header);
    // handle signal if needed (to set checkboxes in all rows, etc.)
    //connect(header, &CheckBoxHeader::checkBoxClicked, this, &MyForm::on_header_checkBoxClicked);
    

提交回复
热议问题