QT代理问题请教Delegate

炫彩灵感 2015-12-17 05:08:43
好吧,语法太烂了,来请教。
#include "spindelegate.h"
#include <QSpinBox>

SpinDelegate::SpinDelegate(QObject *parent):
QItemDelegate(parent)
{
}

QWidget *SpinDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem &/*option*/,const QModelIndex &/*index*/) const
{
QSpinBox *editor = new QSpinBox(parent);
editor->setRange(0,10000);
editor->installEventFilter(const_cast<SpinDelegate*>(this));//为什么这里不是this?而要转换呢?

return editor;
}

void SpinDelegate::setEditorData(QWidget *editor,const QModelIndex &index) const
{
int value =index.model()->data(index).toInt();
QSpinBox *box = static_cast<QSpinBox*>(editor);
box->setValue(value);
}

void SpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const
{
QSpinBox *box = static_cast<QSpinBox*>(editor);
int value = box->value();

model->setData(index,value);
}

void SpinDelegate::updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const
{
editor->setGeometry(option.rect);
}



除了代码中所写的那个问题,还有一个问题就是这里的Qspinbox为什么在每个函数里都定义一个呢?难道不能通用吗?比如createdit函数返回的指针,为什么不能直接拿过来用呢。
...全文
340 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ibm123 2015-12-21
  • 打赏
  • 举报
回复
1、基础没有学好,因为函数后面加有const, 所以才要强制转换。 2、代理类中必须是createEditor中创建一个控件,控件失去焦点就会自动消毁,怎么可能共用一个。
炫彩灵感 2015-12-20
  • 打赏
  • 举报
回复
引用 1 楼 Marcelxx 的回复:
editor->installEventFilter(const_cast<SpinDelegate*>(this)); 不要转换时行的吧,不知道你那里为什么需要那么写,完全没有必要。 QSpinBox 只定义了一个而已,在createEditor里面创建了一个,其余的地方只是为了获取这个控件而已。
我试了,安装过滤器哪里如果不转换,直接使用this,会报错。这个代码是别人的例子。
Marcelxx 2015-12-17
  • 打赏
  • 举报
回复
editor->installEventFilter(const_cast<SpinDelegate*>(this)); 不要转换时行的吧,不知道你那里为什么需要那么写,完全没有必要。 QSpinBox 只定义了一个而已,在createEditor里面创建了一个,其余的地方只是为了获取这个控件而已。

16,199

社区成员

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

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