Qt tableView中的代理继承重写paint函数绘制的图片,不会移动

繁星蓝雨 CSDN会员 繁星蓝雨 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这是代码
#ifndef DELETETOOLBUTTONDELEGATE_H
#define DELETETOOLBUTTONDELEGATE_H

#include <QObject>
#include <QWidget>
#include <QItemDelegate>
#include <QMap>
#include <QStyleOptionButton>
#include <QModelIndex>

class DeleteToolButtonDelegate :public QItemDelegate
{
Q_OBJECT
public:
DeleteToolButtonDelegate(QObject *parent=0);

//自定义代理组件必须继承以下4个函数
//创建编辑组件
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const Q_DECL_OVERRIDE;
//从数据模型获得数据,显示到代理组件中
void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
//将代理组件的数据,保存到数据模型
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const Q_DECL_OVERRIDE;
//更新代理编辑组件的大小
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
const QModelIndex &index) const Q_DECL_OVERRIDE;

void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex & index ) const Q_DECL_OVERRIDE;
private:
QMap<QModelIndex, QStyleOptionButton*> m_btns;

signals:
void deleteCommodityData() const;
};

#endif // DELETETOOLBUTTONDELEGATE_H



void DeleteToolButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{


QStyleOptionButton* button = m_btns.value(index);

if (!button) {
button = new QStyleOptionButton();
button->rect = option.rect.adjusted(0, 0, 0, 0);
//button->rect = QRect(option.rect.left(), option.rect.top(), option.rect.width(), option.rect.height());
//button->text = "X";
button->state |= QStyle::State_Enabled;
button->icon = QIcon(":/Image/sc.png");
button->iconSize = QSize(option.rect.width(), option.rect.height());

(const_cast<DeleteToolButtonDelegate*>(this))->m_btns.insert(index, button);
}
painter->save();

if (option.state & QStyle::State_Selected) {//被选中高亮
painter->fillRect(option.rect, option.palette.highlight());

}
painter->restore();
QApplication::style()->drawControl(QStyle::CE_PushButton, button, painter);
}

...全文
评论 5
收藏 已收藏
分享
返回顶部
繁星蓝雨 CSDN会员
繁星蓝雨 优质创作者: 大数据技术领域 优质创作者: 大数据技术领域领域专家: C/C++技术领域 领域专家: C/C++技术领域
Qt 21,503 成员 26,693 内容