qt- 为来自 tableview 的输入设置验证器

qt- setting validator for input from tableview

我创建了一个 QTableView,它从 QSqlTableModel 获取数据,但我想设置验证,以便从 tableview 更改的值与我的数据格式相同。 我怎样才能做到这一点?

您可以为视图中的项目创建一个自定义委托并覆盖其中的 setModelData 方法以拦截插入格式不正确的数据的尝试:

class MyDelegate: public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit MyDelegate(QObject * parent = 0);

    virtual void setModelData(QWidget * editor, QAbstractItemModel * model,
           const QModelIndex & index) const Q_DECL_OVERRIDE;

Q_SIGNALS:
    void improperlyFormattedDataDetected(int row, int column, QString data);

private:
    bool checkDataFormat(const QString & data) const;
};

MyDelegate::MyDelegate(QObject * parent) :
    QStyledItemDelegate(parent)
{}

void MyDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const
{
    // Assuming the model stores strings so the editor is QLineEdit
    QLineEdit * lineEdit = qobject_cast<QLineEdit*>(editor);
    if (!lineEdit) {
        // Whoops, looks like the assumption is wrong, fallback to the default implementation
        QStyledItemDelegate::setModelData(editor, model, index);
        return;
    }

    QString data = lineEdit->text();
    if (checkDataFormat(data)) {
        // The data is formatted properly, letting the default implementation from the base class set this to the model
        QStyledItemDelegate::setModelData(editor, model, index);
        return;
    }

    // If we got here, the data format is wrong. We should refuse to put the data into the model
    // and probably signal about this attempt to the outside world so that the view can connect to this signal,
    // receive it and do something about it - show a warning tooltip or something.
    emit improperlyFormattedDataDetected(index.row(), index.column(), data);
}

实现自定义委托后,您需要将其设置为您的视图:

view->setItemDelegate(new MyDelegate(view));

我假设您提到的数据格式是一种验证。如果是这样, 另一种方法是添加一个实际的自定义 MyValidator -> QValidator-> 表示派生自)。 @Dmitry 的代码将是相同的,除了您必须在委托中实例化一个 MyValidator 对象作为成员,然后将行编辑器上的验证器设置为:

myValidator = new MyValidator; // some args if you need ...
lineEdit->setValidator (&myValidator);

MyValidator class 中,您应该实现 QValidator class 的纯 virtual QValidator::State validate(QString& input, int& pos) const 方法。您可以将所有格式和验证规则放在那里。

如果不按照您的自定义规则提供正确格式的数据,用户将无法退出行编辑器。无需调用任何其他消息框。

我有一个几乎完全相同的要求,这个解决方案对我来说效果很好!