【发布时间】:2019-07-28 09:46:02
【问题描述】:
我想创建一个正则表达式列表以在我的应用程序中作为单例使用,所以我不必到处写它,我尝试创建 qml QtObject 但它在 qml 中不起作用,因为 qml 和 @ 中没有 RegExp 对象987654321@ 不能作为正则表达式工作,它是一个字符串。 我创建了一个 cpp 类来将我的正则表达式放入其中:
#ifndef UVALIDATORS_H
#define UVALIDATORS_H
#include <QObject>
#include <QRegExp>
#include <QQmlEngine>
#include <QJSEngine>
class UValidators : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(UValidators)
Q_PROPERTY(QRegExp time READ time )
public:
static QObject* instance(QQmlEngine *engine,QJSEngine *scriptEngine){
Q_UNUSED(engine);
Q_UNUSED(scriptEngine);
return new UValidators;
};
explicit UValidators(QObject *parent = nullptr);
QRegExp time() const;
signals:
public slots:
};
#endif // UVALIDATORS_H
对于 cpp :
#include "uvalidators.h"
UValidators::UValidators(QObject *parent) : QObject(parent)
{
}
QRegExp UValidators::time() const{
QRegExp time;
time.setPattern("/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/");
return time;
}
我使用以下方法注册它:
qmlRegisterSingletonType<UValidators>("U",1,0,"Validators",&UValidators::instance);
我是这样使用它的:
TextField{
validator:RegExpValidator{
regExp:U.Validators.time
}
}
一切都很好应用程序运行但文本字段不会让我写任何东西。 有没有办法在 qml 或 cpp 中创建正则表达式列表?
【问题讨论】: