繁体   English   中英

qt-设置验证器以从表视图输入

[英]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-> MyValidator -> QValidator派生自)。 @Dmitry的代码是相同的,除了必须实例化您的委托中的MyValidator对象作为成员,然后在行编辑器上将验证器设置为:

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

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

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

我几乎有完全相同的要求,这个解决方案对我来说非常有用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM