Search code examples
qtuser-interfacetooltipqlineedit

Qt : Tooltip on wrong input


I have a QLineEdit, on which I have set a QRegExpValidator, that allows the user to input only one whitespace between words.
Now I want that whenever the user tries to enter more than one whitespaces, the tooltip of the QLineEdit should show up, but I'm not getting any method to implement it.

Thanx :)


Solution

  • It seems there is no direct method to perform what you want. One way to do above is to handle QLineEdit's textChanged() signal. Then you can check that string against your regular expression using QRegExp::exactMatch() function and if it don't match then show tooltip.

    Connect the signal..

    ...    
    connect(ui->lineEdit,SIGNAL(textChanged(QString)),this,SLOT(onTextChanged(QString)));
    ...
    

    Here your slot goes..

    void MainWindow::onTextChanged(QString text)
    {
        QRegExp regExp;
        regExp.setPattern("[^0-9]*");  // For example I have taken simpler regex..
    
        if(regExp.exactMatch(text))
        {
            m_correctText = text;    // Correct text so far..
            QToolTip::hideText();
        }
        else
        {
            QPoint point = QPoint(geometry().left() + ui->lineEdit->geometry().left(),
                                  geometry().top() + ui->lineEdit->geometry().bottom());
    
            ui->lineEdit->setText(m_correctText);   // Reset previous text..
            QToolTip::showText(point,"Cannot enter number..");
        }
    }