16,211
社区成员
发帖
与我相关
我的任务
分享
QTreeView tree;
tree.setModel(&model);
tree.setItemDelegate(new MyDelegate);
tree.show();
#include "mydelegate.h"
#include <QLineEdit>
MyDelegate::MyDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}
QWidget *MyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */,
const QModelIndex & index ) const
{
if(index.column() == 0) //只对第 0 列采用此方法编辑
{
QLineEdit* box = new QLineEdit(parent);
box->setPlaceholderText("Please input word characters.");
QRegExp rx("\\w+");
QValidator *validator = new QRegExpValidator(rx, box);
box->setValidator(validator);
return box;
}
return NULL;
}
void MyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::EditRole).toString();
QLineEdit* box = static_cast<QLineEdit*>(editor);
box->setText(value);
}
void MyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit* box = static_cast<QLineEdit*>(editor);
model->setData(index, box->text(), Qt::EditRole);
}
void MyDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}