qtableview的单元格怎么放一个button

 我来答
xiangjuan314
2016-03-29 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2924万
展开全部
#ifndef BUTTONDELEGATE_H
#define BUTTONDELEGATE_H

#include <QItemDelegate>

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);

signals:

public slots:

private:
QMap<QModelIndex, QStyleOptionButton*> m_btns;

};

#endif // BUTTONDELEGATE_H
#include "buttondelegate.h"

#include <QApplication>
#include <QMouseEvent>
#include <QDialog>
#include <QPainter>
#include <QStyleOption>
#include <QDesktopWidget>

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 (!button) {
button = new QStyleOptionButton();
button->rect = option.rect.adjusted(4, 4, -4, -4);
button->text = "X";
button->state |= QStyle::State_Enabled;

(const_cast<ButtonDelegate *>(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);

}

bool ButtonDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
if (event->type() == QEvent::MouseButtonPress) {

QMouseEvent* e =(QMouseEvent*)event;

if (option.rect.adjusted(4, 4, -4, -4).contains(e->x(), e->y()) && m_btns.contains(index)) {
m_btns.value(index)->state |= QStyle::State_Sunken;
}
}
if (event->type() == QEvent::MouseButtonRelease) {
QMouseEvent* e =(QMouseEvent*)event;

if (option.rect.adjusted(4, 4, -4, -4).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, 200, 200);
d->move(QApplication::desktop()->screenGeometry().center() - d->rect().center());
d->show();
}
}
}
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式