首页 文章

Qt如果不是十六进制,则从QLineEdit中删除字符

提问于
浏览
1

我的Qt应用程序中有一个QLineEdit需要以十六进制值作为输入 . 如果输入的字符不是十六进制,我希望应用程序显示警告消息框,并从QLineEdit中删除无效字符 . 必须在QLineEdit中每个字符的条目处执行此检查 . 到目前为止,我有这个:

void MemoryTestWindow::on_lineEditAddress1_textChanged(const QString &arg1)
{
        QString text1=ui->lineEditAddress1->text();
        int len=text1.length();
        QChar ch=text1.at(len-1).toUpper();
        if(!((ch>='A'&& ch<='F')|| (ch>='0' && ch<='9')))
        {
            text1.remove(len-1,1);
            //*arg1="";
            QMessageBox::warning(this,"Invalid Character!","Please enter hexadecimal characters 0-9, A-F");

        }

}

我正在使用QLineEdit的textChanged插槽,因为我需要在每个字符输入后执行检查 . 我无法想象如何更改QLineEdit中的值,即在警告消息框中单击“确定”后应删除最后一个无效字符 . 我怎样才能做到这一点?

3 回答

  • 5

    执行此操作的标准方法是使用QValidator

    QRegExpValidator *v = new QRegExpValidator("[a-fA-F0-9]*", this); // or QRegularExpressionValidator
     ui->lineEdit->setValidator(v);
    

    QValidator 继承 QObject 时,您可以使其发出信号以检测用户何时键入无效字符:

    class Validator : public QRegExpValidator
    {
        Q_OBJECT
        public:
            Validator(const QRegExp &rx, QObject *parent = nullptr) : 
                QRegExpValidator(rx, parent)
            {}
    
            State validate(QString &input, int &pos) const override
            {
                State state = QRegExpValidator::validate(input, pos);
                if (state == Invalid)
                    emit error();
                return state;
            }
        signals:
            void error();
    }
    

    然后你只需要连接到 error() 以向用户显示错误:

    Validator *v = new Validator ("[a-fA-F0-9]*", this);
     ui->lineEdit->setValidator(v);
     connect(v, &Validator::error, this, &MyClass::handleWrongInput); 
     // Where handleWrongInput is the slot that handles the error and eventually show an error message
    

    附录

    如果在 MyClass::handleWrongInput() 中,你做的事情导致 QLineEdit 重新调用 QValidator::validate() ,就像更改键盘焦点一样,你将创建一个循环,因为第一次调用 validate() 仍然没有返回 . 要解决此问题,您应该在调用 MyClass::handleWrongInput() 之前调用 validate() .

    为此,最简单的解决方案是使用排队连接:

    connect(v, &Validator::error, this, &MyClass::handleWrongInput, Qt::QueuedConnection);
    
  • 2

    不要重新发明轮子;)使用旨在实现您想要的Qt工具,您可能会获得更好的结果 .

    QLineEdit::mask允许您定义编辑控件中允许的字符 . 特别是,使用 H chars定义掩码将允许您确定控件中允许的十六进制字符数 .

    如果这还不足以满足您的需求,请查看validators以获得更复杂和完整的验证过程 .

  • 1

    ui->lineEditAddress1->setText(text1.remove(len-1, 1)) 怎么样?此外,不确定是否有任何机会工作,但也许 backspace() 方法将工作得很好?

    http://doc.qt.io/qt-4.8/qlineedit.html#backspace

相关问题