6
我有一个QTableView
,我想验证用户输入。 如果用户在QTableView
的单元格中插入了无效值,我想突出显示该单元格并禁用QPushButton
。在QTableView验证用户输入
我该如何做到这一点?我可以使用QValidator
吗?
我有一个QTableView
,我想验证用户输入。 如果用户在QTableView
的单元格中插入了无效值,我想突出显示该单元格并禁用QPushButton
。在QTableView验证用户输入
我该如何做到这一点?我可以使用QValidator
吗?
是的,你可以做到这一点,为此使用自定义QItemDelegate
(我用QIntValidator
作为例子)。
页眉:
#ifndef ITEMDELEGATE_H
#define ITEMDELEGATE_H
#include <QItemDelegate>
class ItemDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit ItemDelegate(QObject *parent = 0);
protected:
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget * editor, const QModelIndex & index) const;
void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const;
void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const;
signals:
public slots:
};
#endif // ITEMDELEGATE_H
.cpp的
#include "itemdelegate.h"
#include <QLineEdit>
#include <QIntValidator>
ItemDelegate::ItemDelegate(QObject *parent) :
QItemDelegate(parent)
{
}
QWidget *ItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QLineEdit *editor = new QLineEdit(parent);
editor->setValidator(new QIntValidator);
return editor;
}
void ItemDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QString value =index.model()->data(index, Qt::EditRole).toString();
QLineEdit *line = static_cast<QLineEdit*>(editor);
line->setText(value);
}
void ItemDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit *line = static_cast<QLineEdit*>(editor);
QString value = line->text();
model->setData(index, value);
}
void ItemDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
用法:
#include "itemdelegate.h"
//...
ItemDelegate *itDelegate = new ItemDelegate;
ui->tableView->setItemDelegate(itDelegate);
在这种情况下,用户将无法输入错误的数据,但可以使用未来:
void ItemDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit *line = static_cast<QLineEdit*>(editor);
QIntValidator validator;
int pos = 0;
QString data = line->text();
if(validator.validate(data,pos) != QValidator::Acceptable)
{
qDebug() << "not valid";//do something
}
else
{
model->setData(index, data);
}
}
但在这种情况下,请不要忘记从您的代码中删除editor->setValidator(new QIntValidator);
行
谢谢,它的工作原理。但是当我插入一个有效的输入时,我不能删除单元格中的数字。我该怎么办? – splunk 2014-10-28 19:57:18
@Aimcorz我想你使用我的第一个例子,所以在我的计算机验证器块输入,但改变选择到另一个单元正常工作。我可以建议你使用我的第二个例子,提供一些方法来避免这种情况,例如设置空字符串'model-> setData(index,“”,Qt :: EditRole);'或其他。 – Chernobyl 2014-10-28 20:05:06