checkbox and itemdelegate in a tableview

后端 未结 6 974
攒了一身酷
攒了一身酷 2020-12-31 22:32

I\'m doing an implementation of a CheckBox that inherits from QitemDelegate, to put it into a QTableView.

the problem is that I get when inserted flush left and I ne

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 22:59

    I solve this problem with the following item delegate:

    booleanitemdelegate.h

    #ifndef BOOLEANITEMDELEGATE_H
    #define BOOLEANITEMDELEGATE_H
    
    #include 
    
    
    
    class BooleanItemDelegate : public QItemDelegate
    {
    public:
        BooleanItemDelegate(QObject *parent);
    
    public:
        void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;public:
        bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
    };
    
    #endif // BOOLEANITEMDELEGATE_H
    

    booleanitemdelegate.cpp

    #include "booleanitemdelegate.h"
    
    BooleanItemDelegate::BooleanItemDelegate(QObject *parent):
        QItemDelegate(parent)
    {
    
    }
    
    void BooleanItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        drawCheck(painter, option, option.rect, index.data().toBool() ? Qt::Checked : Qt::Unchecked);
        drawFocus(painter, option, option.rect);
    }
    
    bool BooleanItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
    {
        if(event->type() == QEvent::MouseButtonRelease){
            model->setData(index, !model->data(index).toBool());
            event->accept();
        }
        return QItemDelegate::editorEvent(event, model, option, index);
    }
    

    I hope, I can help.

提交回复
热议问题