QT 通过Delegate实现向QHeaderView添加组件

353 阅读1分钟

效果

image.png

相关代码

mainwindow.cpp

auto headerView = ui->tblDevices->horizontalHeader();  

headerView->setItemDelegateForColumn(1, new ToolButtonDelegate(headerView));  
headerView->openPersistentEditor(headerView->model()->index(0, 1)); 

headerView->setItemDelegateForColumn(0, new ToolButtonDelegate(headerView));  
headerView->openPersistentEditor(headerView->model()->index(0, 0));

ToolButtonDelegate.cpp

#include <QToolButton>
#include <QHeaderView>

static int l = 18;

ToolButtonDelegate::ToolButtonDelegate(QObject *parent): QStyledItemDelegate(parent) {}

QWidget *ToolButtonDelegate::createEditor(QWidget *parent,
                                          const QStyleOptionViewItem &option,
                                          const QModelIndex &index) const {
    auto btn = new QToolButton(parent);
    btn->setFixedSize(l, l);
    btn->setIconSize(QSize(l, l));
    btn->setIcon(QIcon(":/light_theme/filter.svg"));
    return btn;
}

void ToolButtonDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {}

void ToolButtonDelegate::setModelData(QWidget *editor, 
                                      QAbstractItemModel *model, 
                                      const QModelIndex &index) const {}

void ToolButtonDelegate::updateEditorGeometry(QWidget *editor,
                                              const QStyleOptionViewItem &option,
                                              const QModelIndex &index) const {
    auto headerView = (QHeaderView *) parent();
    // 为什么 option.rect 无效?
    int col = index.column();
    auto w = headerView->sectionSize(col);
    auto x = headerView->sectionPosition(col);
    editor->move(x + w - l, headerView->height() - l);
}