自定义QTreeView中的条目编辑器

               默认情况下QTreeView中的条目在用户双击情况下会产生编辑器,允许用户输入,但是自己用了这么久,每个功能都是不需要的,往往都是右键啊,其它功能键啊,激活编辑器。

               而同时,在项目中,这种原生的编辑器往往都不能满足需求,因为在某些机器测试情况下,会出现怪怪的样子,不是编辑器的高度过窄,就是不能限制用户输入,而这是非常重要的。今天,我们用QItemDelegate生成自己的编辑器(当然编辑器是QLineEdit)。

EditDelegate::EditDelegate(QObject* parent)
:QItemDelegate(parent)
{

}

QWidget* EditDelegate::createEditor(QWidget* parent,
					  const QStyleOptionViewItem& option,
					  const QModelIndex& index) const
{
	QLineEdit* editor = NULL;
	if(index.isValid())
	{
		editor  = new QLineEdit(parent);
		editor->setMaxLength(32);//限制最大只能输入32个字符
		editor->setFixedHeight(20);//调到满意为止

	}
	return editor;
}

void EditDelegate::setEditorData(QWidget* editor,const QModelIndex& index) const
{
		if(index.isValid())
		{
			QLineEdit* lineE = qobject_cast<QLineEdit*>(editor);
			lineE->setText(index.data(Qt::DisplayRole).toString());//text() == data(Qt::DispalyRole).toString()
		}
}

void EditDelegate::setModelData(QWidget* editor,
				  QAbstractItemModel* model, 
				  const QModelIndex& index
				  ) const
{
	if(index.isValid())
	{
		QLineEdit* lineE = qobject_cast<QLineEdit*>(editor);
		model->setData(index,lineE->text());
	}
}

void EditDelegate::updateEditorGeometry(QWidget* editor,
						  const QStyleOptionViewItem& option,
						  const QModelIndex& index
						  ) const
{
	editor->setGeometry(option.rect);
}
二话不说,贴代码(主要来自Qt高级编程一书,感谢作者)

使用的话,当使用QTreeView槽函数edit(位置索引)时,就跳出这个编辑器了,而且还可以通过样式表设置外观,挺不错的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值