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

繁星蓝雨
数据分析领域优质创作者
博客专家认证
2021-02-18 08:48:26
这是代码
#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);
}

...全文
798 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
繁星蓝雨 2021-02-19
  • 打赏
  • 举报
回复
首先非常感谢你的回答,但是QStyleOptionButton没有您描述的构造函数
atuexe 2021-02-19
  • 打赏
  • 举报
回复
删除的按钮指定父窗口就可以了 button = new QStyleOptionButton(this);
繁星蓝雨 2021-02-18
  • 打赏
  • 举报
回复
谢谢🙏,各位大佬
繁星蓝雨 2021-02-18
  • 打赏
  • 举报
回复
就是删除那个小图标,不会随着滑动拦移动
繁星蓝雨 2021-02-18
  • 打赏
  • 举报
回复

16,203

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧