0

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 :)

Jaydeep Solanki
  • 2,895
  • 5
  • 36
  • 50

2 Answers2

2

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..");
    }
}
Ammar
  • 1,947
  • 14
  • 15
  • I got your idea, but there would be two problems with this approach: 1) I'm using a QRegExpValidator, which means that I don't want the user to input any invalid string, while using your approach, the user will be able to enter invalid input 2) I don't know how to programmatically show tooltip :D – Jaydeep Solanki May 14 '12 at 14:50
  • @Jaydeep: That can be solved, you can always store the correct string in another variable say `m_correctText`. Whenever regex match fails, you reset using `QLineEdit::setText(m_correctText)`.. Ya regarding the tooltip [check this](http://doc.qt.nokia.com/4.7-snapshot/widgets-tooltips.html).. Or another suggestion would be to show `QLabel` with red text, positioned at right-side of `QLineEdit` control. :) – Ammar May 14 '12 at 15:19
  • @Jaydeep: I have updated my answer by adding working example code.. :) – Ammar May 15 '12 at 05:57
  • this is kinda what I wanted, but I get it.. Now i'll be able to make it work in my app... Thanks !! – Jaydeep Solanki May 15 '12 at 09:03
0

I don't remember explicit API for showing a tooltip. I'm afraid you'll have to go with popping up a custom tool window (i.e. a parent-less QWidget) to achieve the desired result.

If you want to style your own popup window like a standard tooltip, QStyle should have something for that. If in doubt, read into the Qt source code where it renders the tooltip. That'll tell you which style elements to use.

Stefan Majewsky
  • 5,427
  • 2
  • 28
  • 51