QT 在tableview表头添加复选框

5 篇文章 0 订阅

QT 在tableview表头添加复选框

上一篇已经在第一列中添加了复选框,本篇实在表头添加复选框并对其信号与槽进行关联,基本都是把别人的代码拿过来改改
https://blog.csdn.net/qq_44257811/article/details/120266599
效果图
重写QHeaderView的方法painSection

class TableHeaderView:public QHeaderView
{
    Q_OBJECT
public:
    TableHeaderView(Qt::Orientation orientation, QWidget *parent);
    ~TableHeaderView();

public:
    void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
    bool event(QEvent *e) Q_DECL_OVERRIDE;
    void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
    void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
public slots:
    void onStateChanged(int state);
signals:
    void stateChanged(int state);

public:
    bool m_bPressed;
    bool m_bChecked;
    bool m_bTristate;
    bool m_bNoChange;
    bool m_bMoving;
};
#define CHECK_BOX_COLUMN 0
#define File_PATH_COLUMN 1


TableHeaderView::TableHeaderView(Qt::Orientation orientation, QWidget *parent)
    : QHeaderView(orientation, parent),
      m_bPressed(false),
      m_bChecked(false),
      m_bTristate(false),
      m_bNoChange(false),
      m_bMoving(false)
{
    setSectionsClickable(true);
}

TableHeaderView::~TableHeaderView()
{

}

// 槽函数,用于更新复选框状态
void TableHeaderView::onStateChanged(int state)
{
    if (state == Qt::PartiallyChecked)
    {
        m_bTristate = true;
        m_bNoChange = true;
    }
    else
    {
        m_bNoChange = false;
    }
    m_bChecked = (state != Qt::Unchecked);
    update();
}


// 绘制复选框
void TableHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
    painter->save();
        QHeaderView::paintSection(painter, rect, logicalIndex);
        painter->restore();
        if (logicalIndex == CHECK_BOX_COLUMN)
        {
            QStyleOptionButton option;
            option.initFrom(this);

            if (m_bChecked)
                option.state |= QStyle::State_Sunken;

            if (m_bTristate && m_bNoChange)
                option.state |= QStyle::State_NoChange;
            else
                option.state |= m_bChecked ? QStyle::State_On : QStyle::State_Off;
            if (testAttribute(Qt::WA_Hover) && underMouse()) {
                if (m_bMoving)
                    option.state |= QStyle::State_MouseOver;
                else
                    option.state &= ~QStyle::State_MouseOver;
            }

            QCheckBox checkBox;
            option.rect = QRect(5,5,20,20);//绘制复选框的位置与大小
            style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter, &checkBox);
        }
}

// 鼠标按下表头
void TableHeaderView::mousePressEvent(QMouseEvent *event)
{
    int nColumn = logicalIndexAt(event->pos());
    if ((event->buttons() & Qt::LeftButton) && (nColumn == CHECK_BOX_COLUMN))
    {
        m_bPressed = true;
    }
    else
    {
        QHeaderView::mousePressEvent(event);
    }
}

// 鼠标从表头释放,发送信号,更新model数据
void TableHeaderView::mouseReleaseEvent(QMouseEvent *event)
{
    if (m_bPressed)
    {
        if (m_bTristate && m_bNoChange)
        {
            m_bChecked = true;
            m_bNoChange = false;
        }
        else
        {
            m_bChecked = !m_bChecked;
        }

        update();

        Qt::CheckState state = m_bChecked ? Qt::Checked : Qt::Unchecked;
        emit stateChanged(state);
    }
    else
    {
        QHeaderView::mouseReleaseEvent(event);
    }

    m_bPressed = false;
}


// 鼠标滑过、离开,更新复选框状态
bool TableHeaderView::event(QEvent *event)
{
    updateSection(0);
    if (event->type() == QEvent::Enter || event->type() == QEvent::Leave)
    {
        QMouseEvent *pEvent = static_cast<QMouseEvent *>(event);
        int nColumn = logicalIndexAt(pEvent->x());
        if (nColumn == CHECK_BOX_COLUMN)
        {
            m_bMoving = (event->type() == QEvent::Enter);
            update();
            return true;
        }
    }
    return QHeaderView::event(event);
}

然后对第一列和和表头进行关联

    connect(pHeader, SIGNAL(stateChanged(int)), tabModelCar, SLOT(onStateChanged(int)));//连接复选框
    connect(tabModelCar, SIGNAL(stateChanged(int)), pHeader, SLOT(onStateChanged(int)));//连接复选框

基本就这样吧,也不讲解了,以前理解的忘记完了,写写文章希望下次不会的时候有东西可以参考,加油,搬砖人!

  • 5
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: 在Qt中使用QTableView添加复选框可以通过自定义委托实现。首先,我们需要创建一个自定义的委托类来设置单元格的编辑控件为复选框。 ```cpp class CheckBoxDelegate : public QItemDelegate { public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override { QStyleOptionButton checkboxStyle; checkboxStyle.state |= QStyle::State_Enabled | QStyle::State_Active; if (index.data(Qt::CheckStateRole).toBool()) checkboxStyle.state |= QStyle::State_On; else checkboxStyle.state |= QStyle::State_Off; checkboxStyle.rect = option.rect.adjusted(0, 0, -1, -1); QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxStyle, painter); } QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override { QCheckBox *editor = new QCheckBox(parent); editor->setAttribute(Qt::WA_TransparentForMouseEvents); editor->setChecked(index.data(Qt::CheckStateRole).toBool()); connect(editor, SIGNAL(clicked(bool)), this, SLOT(commitAndCloseEditor())); return editor; } void setEditorData(QWidget *editor, const QModelIndex &index) const override { QCheckBox *checkBox = static_cast<QCheckBox*>(editor); checkBox->setChecked(index.data(Qt::CheckStateRole).toBool()); } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override { QCheckBox *checkBox = static_cast<QCheckBox*>(editor); model->setData(index, checkBox->isChecked(), Qt::CheckStateRole); } void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override { editor->setGeometry(option.rect); } private slots: void commitAndCloseEditor() { QCheckBox *editor = static_cast<QCheckBox*>(sender()); emit commitData(editor); emit closeEditor(editor); } }; ``` 接下来,在创建QTableView并设置model之后,我们可以为需要添加复选框的列设置自定义委托。 ```cpp QTableView tableView; QStandardItemModel model(10, 3); // 例如,创建一个10行3列的模型 tableView.setModel(&model); CheckBoxDelegate delegate; tableView.setItemDelegateForColumn(2, &delegate); // 为第3列设置自定义委托 ``` 通过这样的方式,我们可以在QTableView中的指定列上显示复选框,并实现相应的操作。 ### 回答2: QtTableView通过使用QCheckBox作为模型元素来添加复选框。可以通过实现自定义的委托类来启用这个功能。 首先,需要创建一个新的委托类,继承QItemDelegate。在这个委托类中,重写createEditor()和setEditorData()方法,并使用QCheckBox作为编辑器。 以下是一个示例: ```cpp #include <QtWidgets> class CheckBoxDelegate : public QItemDelegate { public: CheckBoxDelegate(QObject *parent = nullptr) : QItemDelegate(parent) { } QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override { Q_UNUSED(option) Q_UNUSED(index) QCheckBox *editor = new QCheckBox(parent); return editor; } void setEditorData(QWidget *editor, const QModelIndex &index) const override { QCheckBox *checkBox = qobject_cast<QCheckBox*>(editor); if (checkBox) { bool checked = index.model()->data(index, Qt::DisplayRole).toBool(); checkBox->setChecked(checked); } } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override { QCheckBox *checkBox = qobject_cast<QCheckBox*>(editor); if (checkBox) { model->setData(index, checkBox->isChecked(), Qt::EditRole); } } }; ``` 接下来,在TableView中使用这个自定义委托类。例如: ```cpp int main(int argc, char *argv[]) { QApplication app(argc, argv); QStandardItemModel model(4, 2); QTableView tableView; CheckBoxDelegate checkBoxDelegate; tableView.setItemDelegateForColumn(0, &checkBoxDelegate); tableView.setModel(&model); tableView.show(); return app.exec(); } ``` 这样,TableView的第一列将显示复选框。您可以通过在模型中设置数据来更改复选框的状态,例如: ```cpp QStandardItem *item = new QStandardItem(); item->setCheckable(true); item->setData(Qt::Unchecked, Qt::CheckStateRole); model->setItem(row, 0, item); ``` 这样,当您运行应用程序时,您应该能够在TableView中看到具有复选框的行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值