checkbox and itemdelegate in a tableview

后端 未结 6 1016
攒了一身酷
攒了一身酷 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:51

    If you are extending the QItemDelegate class, it has a drawCheck() function, what will draw you a nince, centered checkbox. You can use it in the paint() function.

    Edit:

    Here is an example, assuming you have a class called BooleanEditor, what inherits from QItemDelegate:

    void BooleanEditor::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);
    }
    

    For keeping the checkbox centered when entering the edit mode, you can do something like this:

    class BooleanWidget : public QWidget
    {
        Q_OBJECT
        QCheckBox * checkBox;
    
        public:
        BooleanWidget(QWidget * parent = 0)
        {
            checkBox = new QCheckBox(this);
            QHBoxLayout * layout = new QHBoxLayout(this);
            layout->addWidget(checkBox,0, Qt::AlignCenter);
        }
    
        bool isChecked(){return checkBox->isChecked();}
        void setChecked(bool value){checkBox->setChecked(value);}
    };
    

    And in your ItemDelegates createEditor() method return an instance of this BooleanWidget class. In your setModelData() and setEditorData() you can now cast your input widget to this BooleanWidget:

    BooleanWidget * widget = qobject_cast(editor);
    

    and then use the is/setChecked method.

提交回复
热议问题