验证QTableView中的用户输入

时间:2014-10-28 17:27:01

标签: qt qtableview qvalidator

我有一个QTableView,我想验证用户输入。 如果用户在QTableView的单元格中插入无效值,我想突出显示该单元格并停用QPushButton

我怎样才能做到这一点?我可以使用QValidator吗?

1 个答案:

答案 0 :(得分:11)

是的,您可以执行此操作,为此目的使用自定义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);