PDA

View Full Version : QT - My way to force numeric input


shep
02-15-2010, 05:15 PM
This is probably lame, but I thought I'd share my method for making a lineEdit into a numeric only input.


void MainWindow::on_lineEdit_textChanged(QString )
{
QString qNewValue = ui->lineEdit->text();
bool ok;
double dTest = qNewValue.toDouble(&ok);
int dotCnt=0;
if (!ok)
{
QString qStripped;

for (int i=0; i< qNewValue.length(); i++ )
{
QString subStr = qNewValue.at(i);
QString sValid = "1234567890.";
if (subStr.toLower() == ":")
{
subStr = ".";
}
if (subStr.toLower() == "?")
{
subStr = ".";
}

if (subStr==".")
{
dotCnt++;
}
if (subStr.toLower() == "q")
{
subStr = "1";
}
if (subStr.toLower() == "w")
{
subStr = "2";
}
if (subStr.toLower() == "e")
{
subStr = "3";
}
if (subStr.toLower() == "r")
{
subStr = "4";
}
if (subStr.toLower() == "t")
{
subStr = "5";
}
if (subStr.toLower() == "y")
{
subStr = "6";
}
if (subStr.toLower() == "u")
{
subStr = "7";
}
if (subStr.toLower() == "i")
{
subStr = "8";
}
if (subStr.toLower() == "o")
{
subStr = "9";
}
if (subStr.toLower() == "p")
{
subStr = "0";
}
if ( (sValid.contains( subStr)) && (dotCnt <= 1))
{
qStripped.append(subStr);
}
}
ui->lineEdit->setText(qStripped);
}

}


Hopes this helps someone.

b666m
02-15-2010, 05:17 PM
set your code into the code-tag [.code] [./code] (of course without the . ) :)

shep
02-15-2010, 05:21 PM
set your code into the code-tag [.code] [./code] (of course without the . ) :)

Done, thanks!

qwerty12
02-15-2010, 05:30 PM
What about ze Germans with their QWERTZ keyboards? (Being qwerty12, I have to boo at the Germans for using the QWERTZ layout on their keyboards anyway, but... :p)

w00t
02-15-2010, 05:31 PM
I'd suggest looking at:

http://doc.trolltech.com/4.6/qwidget.html#inputMethodHints-prop

and

http://doc.trolltech.com/4.6/qlineedit.html#inputMask-prop

and

http://doc.trolltech.com/4.6/qlineedit.html#setValidator

Hope this helps.

shep
02-15-2010, 05:40 PM
What about ze Germans with their QWERTZ keyboards? (Being qwerty12, I have to boo at the Germans for using the QWERTZ layout on their keyboards anyway, but... :p)

I did say it sucked :p

If you forget about the qwertyuiop to 1234567890 translation then the basic principle is sound! Just did the translation for lazy old me.

Shep

shep
02-15-2010, 05:42 PM
I'd suggest looking at...

Thanks woot, unfortunately the inputHints don't work using Madde at the moment :( that's why I went looking for an alt in the first place.

Thanks for the tips though

w00t
02-15-2010, 06:46 PM
Thanks woot, unfortunately the inputHints don't work using Madde at the moment :( that's why I went looking for an alt in the first place.

Thanks for the tips though

Ah. Yeah, they're new to Qt 4.6, and MADDE has 4.5 at the moment... *but*, input hints are only for the virtual keyboard. The actual restriction of input can be done through validators :)