我有一个Qt小部件,它只接受十六进制字符串作为输入 . 将输入字符限制为 [0-9A-Fa-f]
非常简单,但我希望在"bytes"之间显示分隔符,例如,如果分隔符是空格,并且用户输入 0011223344
,我希望行编辑显示 00 11 22 33 44
现在如果用户按下退格键3次,那么我希望它显示 00 11 22 3
.
我 almost 有我想要的,到目前为止只有一个微妙的错误涉及使用删除键删除分隔符 . 有没有人有更好的方法来实现这个验证器?到目前为止,这是我的代码:
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
内部缓冲区中的实际字符分开,但我不知道从哪里开始,我想这是一项非平凡的任务 .
本质上,我想有一个符合这个正则表达式的Validator: "[0-9A-Fa-f]( [0-9A-Fa-f])*"
但我不希望用户必须输入一个空格作为分隔符 . 同样,在编辑它们键入的内容时,应该隐式管理这些空格 .
3 回答
埃文,试试这个:
inputMask负责间距,“h”代表可选的十六进制字符(“H”代表非可选字符) . 唯一的缺点:您必须提前知道最大输入长度 . 我上面的例子只允许四个字节 .
最好的问候,罗宾
我将提出三种方法:
当只剩下
QLineEdit
光标的字符是一个空格时,你可以重新实现QLineEdit::keyPressEvent()
以不同的方式处理反斜杠 . 使用此方法,您还可以在键入新字符时自动添加空格 .另一种方法是创建一个连接到
QLineEdit::textChanged()
信号的新插槽 . 更改文本时会发出此信号 . 在此插槽中,您可以根据需要处理空间的创建和删除 .最后,您可以创建一个新类,派生自
QLineEdit
,重新实现QLineEdit::paintEvent()
方法 . 使用此方法,您可以显示未存储在QLineEdit
缓冲区中的十六进制单词之间的空格 .Robin的解决方案很好并且有效 . 但我认为你可以做得最好!
用于输入掩码:
在ui中,R-click on lineEdit - > Go to Slots ... - > textChanged . 在插槽函数中编写此代码:
现在你有一个带有十六进制输入的lineEdit,大写,带有破折号分隔符 .
有一个很好的代码时间:)