【发布时间】:2011-02-15 03:44:18
【问题描述】:
我有一个 Qt 小部件,它应该只接受一个十六进制字符串作为输入。将输入字符限制为[0-9A-Fa-f] 非常简单,但我想让它在“字节”之间显示一个定界符,例如,如果定界符是空格,并且用户键入0011223344 我想要行编辑以显示 00 11 22 33 44 现在如果用户按退格键 3 次,那么我希望它显示 00 11 22 3。
我几乎有我想要的,到目前为止只有一个微妙的错误涉及使用删除键删除分隔符。有没有人有更好的方法来实现这个验证器?到目前为止,这是我的代码:
class HexStringValidator : public QValidator {
public:
HexStringValidator(QObject * parent) : QValidator(parent) {}
public:
virtual void fixup(QString &input) const {
QString temp;
int index = 0;
// every 2 digits insert a space if they didn't explicitly type one
Q_FOREACH(QChar ch, input) {
if(std::isxdigit(ch.toAscii())) {
if(index != 0 && (index & 1) == 0) {
temp += ' ';
}
temp += ch.toUpper();
++index;
}
}
input = temp;
}
virtual State validate(QString &input, int &pos) const {
if(!input.isEmpty()) {
// TODO: can we detect if the char which was JUST deleted
// (if any was deleted) was a space? and special case this?
// as to not have the bug in this case?
const int char_pos = pos - input.left(pos).count(' ');
int chars = 0;
fixup(input);
pos = 0;
while(chars != char_pos) {
if(input[pos] != ' ') {
++chars;
}
++pos;
}
// favor the right side of a space
if(input[pos] == ' ') {
++pos;
}
}
return QValidator::Acceptable;
}
};
目前,这段代码的功能已经足够了,但我希望它能够按预期 100% 工作。显然,理想的做法是将十六进制字符串的显示与存储在QLineEdit 的内部缓冲区中的实际字符分开,但我不知道从哪里开始,我想这是一项不平凡的工作。
本质上,我希望有一个符合这个正则表达式的验证器:"[0-9A-Fa-f]( [0-9A-Fa-f])*",但我不希望用户输入空格作为分隔符。同样,在编辑他们键入的内容时,应隐式管理空格。
【问题讨论】: