英雄不问,饮水思源~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
一、基于继承 QStyledItemDelegate 代理添加按键
二、基于继承 QItemDelegate 的代理类添加按键
#include
<QApplication>
#include
<QMouseEvent>
#include
<QDialog>
#include
<QPainter>
#include
<QStyleOption>
#include
<QDesktopWidget>
#include
<QDebug>
#include
<QMap>
#include
<QItemDelegate>
1、创建自己的代理类
buttondelegate.h
class
ButtonDelegate
:
public
QItemDelegate
{
Q_OBJECT
public:
explicit
ButtonDelegate(
QObject
*parent
=
0);
//重写绘图事件
void
paint(
QPainter
*painter,
const
QStyleOptionViewItem
&option,
const
QModelIndex
&index)
const;
//重写事件过滤
bool
editorEvent(
QEvent
*event,
QAbstractItemModel
*model,
const
QStyleOptionViewItem
&option,
const
QModelIndex
&index);
private:
QMap<
QModelIndex,
QStyleOptionButton*>
m_btns;
};
buttondelegate.cpp
int
FILE_OPERATE_COLUMN = 4;//
按键所在列
ButtonDelegate::ButtonDelegate(
QObject
*parent)
:
QItemDelegate(parent)
{}
void
ButtonDelegate::
paint(
QPainter
*painter,
const
QStyleOptionViewItem
&option,
const
QModelIndex
&index)
const
{
QStyleOptionButton*
button
=
m_btns.value(index);
//在特定的索引处绘制按键,这个变量临时存储绘制的按键信息
//如果为按键列绘制按键
if
(
index
.
column
()
==
FILE_OPERATE_COLUMN)
{
//非常重要!该条件最好为判断索引与需要代理的列!因为这样绘制的按键会随滑动条进行重绘!
button
=
new
QStyleOptionButton();//绘制存button的参数的对象
button->
features
=
QStyleOptionButton::
None;
//设置为pushButton类型,可以按下
button->
rect
=
option.
rect.adjusted(
1,
1,
-
1,
-
1);//绘制尺寸
button->
text
=
tr(
"开始检验");
button->
state
|=
QStyle::
State_Enabled;
(
const_cast<
ButtonDelegate
*>(
this))->
m_btns.insert(index,
button);//将绘制的按键放入Qmap
}
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);
}
//事件选择过滤
bool
ButtonDelegate::
editorEvent(
QEvent
*event,
QAbstractItemModel
*model,
const
QStyleOptionViewItem
&option,
const
QModelIndex
&index)
{
if
(event->type()
==
QEvent::
MouseButtonPress)
{
qDebug()<<
"--------";
QMouseEvent*
e
=(
QMouseEvent*)event;
//确定鼠标点击的位置在画的按键中
if
(option.rect.adjusted(1,
1,
-1,
-1).contains(e->x(),
e->y())
&&
m_btns.contains(index))
{
m_btns.value(index)->state
|=
QStyle::State_Sunken;
/***************/
}
}
if
(event->type()
==
QEvent::
MouseButtonRelease)
{
qDebug()<<
"++++++++";
QMouseEvent*
e
=(
QMouseEvent*)event;
//
if
(option.rect.adjusted(1,
1,
-1,
-1).contains(e->x(),
e->y())
&&
m_btns.contains(index))
{
//
m_btns.value(index)->state
&=
(~QStyle::State_Sunken);
//
QDialog
*d
=
new
QDialog();
//
d->setGeometry(0,
0,
100,
100);
//
d->move(QApplication::desktop()->screenGeometry().center()
-
d->rect().center());
//
d->show();
//
}
}
}
2、调用自己的类
//设置代理
m_buttonDelegate
=
new
ButtonDelegate(
this);
ui->
tableView->setItemDelegateForColumn(
FILE_OPERATE_COLUMN ,
m_buttonDelegate);