【问题标题】:checkbox and itemdelegate in a tableview表格视图中的复选框和 itemdelegate
【发布时间】:2023-03-20 12:15:01
【问题描述】:

我正在实现一个继承自 QitemDelegate 的 CheckBox,将其放入 QTableView。

问题是当我插入左对齐时我需要它居中。

据我了解,负责绘制的方法。我是这样写的:

void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
bool checkValue;

QStyleOptionButton BtnStyle;
BtnStyle.state = QStyle::State_Enabled;

if(index.model()->data(index, Qt::DisplayRole).toBool() == true)
{
BtnStyle.state |= QStyle::State_On;
checkValue = true;
}else{
BtnStyle.state |= QStyle::State_Off;
checkValue = false;
}


BtnStyle.direction = QApplication::layoutDirection();
BtnStyle.rect = option.rect;
QApplication::style()->drawControl(QStyle::CE_CheckBox,&BtnStyle,painter );
QApplication::style()->drawControl(QStyle::CE_CheckBox,&BtnStyle,painter );
}

居中缺少什么?

所以我有委托:

.h

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

class CheckBoxDelegate : public QItemDelegate
{
    Q_OBJECT
private:
    BooleanWidget *checkbox;

public:
    CheckBoxDelegate(QObject *parent);
    ~CheckBoxDelegate();
    void setEditorData( QWidget *editor,const QModelIndex &index )const;
    void setModelData( QWidget *editor,QAbstractItemModel *model,const QModelIndex &index )const;
    QWidget *createEditor( QWidget *parent,const QStyleOptionViewItem &/* option */,const QModelIndex &/* index */ )const;
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;

public slots:
    void changed( bool );

};

.cpp

void CheckBoxDelegate::changed( bool value )
{
    BooleanWidget *checkbox = static_cast<BooleanWidget*>( sender() );
    emit commitData( checkbox );
    emit closeEditor( checkbox );
}

QWidget *CheckBoxDelegate::createEditor( QWidget *parent,const QStyleOptionViewItem &/* option */,const QModelIndex &/* index */ ) const
{
  BooleanWidget *editor = new BooleanWidget( parent );
  connect( editor, SIGNAL( toggled ( bool ) ), this, SLOT( changed( bool ) ) );

  return editor;
}

void CheckBoxDelegate::setEditorData( QWidget *editor,const QModelIndex &index ) const
{
    int value = index.model()->data(index, Qt::DisplayRole).toInt();

    BooleanWidget *checkbox = static_cast<BooleanWidget*>(editor);

    if(value == 1)
    {
        checkbox->setChecked(true);
    }
    else
    {
        checkbox->setChecked(false);
    }


}

void CheckBoxDelegate::setModelData( QWidget *editor,QAbstractItemModel *model,const QModelIndex &index ) const
{
    BooleanWidget *checkBox = qobject_cast<BooleanWidget*>( editor );
    Qt::CheckState value;

    if(checkBox->isChecked())
        value = Qt::Checked;
    else
        value = Qt::Unchecked;

    model->setData( index, value, Qt::DisplayRole);
}

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

【问题讨论】:

    标签: qt qtableview qitemdelegate qcheckbox


    【解决方案1】:

    如果您要扩展 QItemDelegate 类,它有一个 drawCheck() 函数,它会为您画出一个居中的复选框。你可以在paint()函数中使用它。

    编辑:

    这是一个示例,假设您有一个名为 BooleanEditor 的类,它继承自 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);
    }
    

    为了在进入编辑模式时保持复选框居中,您可以执行以下操作:

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

    并且在您的 ItemDelegates createEditor() 方法中返回此 BooleanWidget 类的实例。在您的 setModelData() 和 setEditorData() 中,您现在可以将输入小部件投射到此 BooleanWidget:

    BooleanWidget * widget = qobject_cast<BooleanWidget*>(editor);
    

    然后使用 is/setChecked 方法。

    【讨论】:

    • 可以举个例子吗?因为据我所知,该函数的构造如下: drawCheck(QPainter *painter, const QStyleOptionViewItem &option,QRect &rect,Qt::state);
    • 我添加了一个例子。如果你想让它可编辑(不仅仅是显示),那么你也应该覆盖你的 tablemodels flags() 函数。
    • 好的,谢谢,我解决了部分问题。支票居中。现在的问题是我在 QTableView 中有它的检查,并且通过单击检查将其移动到左侧而没有选择。我必须双击才能被选中
    • 所有 Qt itemdelegates 编辑器模式只有在双击时才会被激活。我试图自己找到一种方法来解决这个复选框问题,但它可能会比它的价值更麻烦。
    • 我如何停止点击表格以将支票向左移动?
    【解决方案2】:

    我使用以下项目委托解决了这个问题:

    booleanitemdelegate.h

    #ifndef BOOLEANITEMDELEGATE_H
    #define BOOLEANITEMDELEGATE_H
    
    #include <QItemDelegate>
    
    
    
    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);
    }
    

    希望,我能帮上忙。

    【讨论】:

    • 对我来说这是最好的答案,因为这是最简单的,而且效果很好
    • 这是最好的答案之一。非常简单且有效
    • 也来自我。这是最好的答案。它必须放在顶部!
    【解决方案3】:

    这就是我为使编辑器控件居中对齐所做的:

    QWidget *checkBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
        QCheckBox *editor = new QCheckBox(parent);
        editor->setTristate(allowTriState); //my class' variable
        // this does the trick :)
        editor->setStyleSheet("QCheckBox {margin-left: 43%; margin-right: 57%;}"); 
        // this should do it better
        // editor->setStyleSheet("QCheckBox {margin-left: auto; margin-right: auto;}");
        // but in my case the checkbox is slightly to the left of original
        return editor;
    }
    

    【讨论】:

      【解决方案4】:

      解决问题如下:

      相信从itemDelegate继承QStyledItemDelegate并重新实现方法“paint”和“editorEvent”。

      在“editorEvent”方法中发出一个信号,指示选择了哪一行。

      这里是代码

      class ItemDelegate : public QStyledItemDelegate
      {
          Q_OBJECT
      
      signals:
          void clickSignal(int);
      
      
      public:
          ItemDelegate(QObject *parent = 0)
              : QStyledItemDelegate(parent)
          {
          }
      
          void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
          {
              QStyleOptionViewItemV4 viewItemOption(option);
      
              if (index.column() == 0) {
                  const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
                  QRect newRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                                                      QSize(option.decorationSize.width() + 5,option.decorationSize.height()),
                                                      QRect(option.rect.x() + textMargin, option.rect.y(),
                                                            option.rect.width() - (2 * textMargin), option.rect.height()));
                  viewItemOption.rect = newRect;
              }
              QStyledItemDelegate::paint(painter, viewItemOption, index);
      
          }
      
          virtual bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
                                   const QModelIndex &index)
          {
              Q_ASSERT(event);
              Q_ASSERT(model);
      
              // make sure that the item is checkable
              Qt::ItemFlags flags = model->flags(index);
              if (!(flags & Qt::ItemIsUserCheckable) || !(flags & Qt::ItemIsEnabled))
                  return false;
              // make sure that we have a check state
              QVariant value = index.data(Qt::CheckStateRole);
              if (!value.isValid())
                  return false;
              // make sure that we have the right event type
              if (event->type() == QEvent::MouseButtonRelease) {
                  const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
                  QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                                                        option.decorationSize,
                                                        QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
                                                              option.rect.width() - (2 * textMargin),
                                                              option.rect.height()));
      
              } else {
                  return false;
              }
              Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked
                                      ? Qt::Unchecked : Qt::Checked);
      
      
      
      
              emit(clickSignal(index.row()));
      
              return model->setData(index, state, Qt::CheckStateRole);
          }
      
      
      };
      

      我有一个连接 QTableView 的类这样做:

      connect(check,SIGNAL(clickSignal(int)),this,SLOT(CheckMark(int))); //check the itemDelegate
      

      使用标记的检查执行操作

      【讨论】:

        【解决方案5】:

        不用大惊小怪,直接设置rect:

        BtnStyle.rect = option.rect;
        

        构造一个新的 QRect 并将 x 坐标尽可能向右移动:

        QRect r = option.rect;
        QRect r1(r.x() + 34, r.y(), r.width(), r.height());
        BtnStyle.rect = r1;
        

        【讨论】:

          【解决方案6】:

          Python 中的解决方案使复选框居中并允许用户选中/取消选中 here

          【讨论】:

            猜你喜欢
            • 2010-11-04
            • 1970-01-01
            • 1970-01-01
            • 2011-08-06
            • 1970-01-01
            • 2012-03-09
            相关资源
            最近更新 更多