默认情况下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(位置索引)时,就跳出这个编辑器了,而且还可以通过样式表设置外观,挺不错的。