我正在QT GUI项目中编写自定义QValidator,我的理解是我需要扩展QValidator类,因为:
void setValidator(const QValidator *);
需要通过QValidator
子类。问题是功能:
virtual QValidator::State validate(QString& input, int& pos) const Q_DECL_OVERRIDE;
是const,但是我需要在子类中写入验证状态,并且由于此const属性,我无法写入任何成员变量。我该如何解决这个API约束?
我正在做这样的事情:
QValidator::State IPv4Validator::validate(QString &input, int &pos) const
{
auto validationResult = QRegExpValidator::validate(input, pos);
// custom logic here:
myMemberVariable = something(validationResult);
// more logic
// more logic
// more logic
return validationResult;
}
预先感谢!
您可以通过声明成员变量mutable
或使用const_cast
(不安全)来编写const
函数中的成员变量。
struct A {
void foo() const {
a = 3;
const_cast<A*>(this)->b = 4;
}
mutable int a;
int b;
};
阅读您的评论后,我意识到我需要在QValidator
子类之外委派自定义逻辑。谢谢你的回复!他们帮助我了解了我做错了什么。