概述
一个需求是表格中只能填 0 到 18 的数字,因此通过委托来实现。
函数
createEditor
返回在 QTableView 中使用的控件,就在这边用正则限制输入的数据。
setEditorData
从指定的数据模型设置要由编辑器显示和编辑的数据
setModelData
从 editor 小部件获取数据,并将数据存储在项目索引处的数据模型中。
updateEditorGeometry
根据给定的样式选项,更新 index 指定项的编辑器。
代码
实现
class TableDelegate: public QItemDelegate
{
Q_OBJECT
public:
TableDelegate(QObject *parent = 0): QItemDelegate(parent) { }
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QLineEdit *editor = new QLineEdit(parent);
QRegExp regExp("0[0-9]|1[0-8]|"); // 正则表达式
editor->setValidator(new QRegExpValidator(regExp, parent));
return editor;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString text = index.model()->data(index, Qt::EditRole).toString();
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
lineEdit->setText(text);
}
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
QString text = lineEdit->text();
model->setData(index, text, Qt::EditRole);
}
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
};
#endif // MAINWINDOW_H
调用
TableDelegate*editDelegate = new TableDelegate();
// 设置第一列
tableView->setItemDelegateForColumn(0, editDelegate);
结果
只有第一列表格中的数据只能输入 0-18 的数,不能输入英文符号等,而其他列都可以自由输入任意值。
网友评论