Format percentage column
I have a decimal database column that stores percentages values, for example 0.05 is 5% and 0.2 = 20%.
I have a custom model inherited from QSQLTableModel for this table and want to modify it to display 20% on all QlineEdits I use on my views instead of 0.2
How can I do it?
I have already overridden the data function on my custom model to display it correctly on a QTreeView, but it doesn’t work for QlineEdits:
- {
- if(!index.isValid())
- if (index.column() == CUSTOMERS_DISCOUNT)
- {
- }
- return value;
- }
9 replies
@broadpeak:
I think the code abibiano posted is correct in this sense. He first retreives the value the baseclass returns (which might be an invalid QVariant) and only then checks if the role & column match the ones he is interested in. You are right in general, but in this case, it is handled by the base class.
@Andre
Ahhh, yes, you are right!
But, if abibiano doesn’t want to modify the “percent”, it would be much better solution, that he in the SQL query can “translate” the float to percent (means: using “as” and some computation in SQL). But, if he want to modify the percent, he has to use delegate (createeditor() family) for the app.
I think. Hm, in theory, the first snippet shoulda work :S
Thanks for replay, as you can suppose I’m newbie on QT
If it is easier to implement, I can store in the DB the value as percent (instead of 0.1 as 10), but I continue with the problem to display the % sign after the value on edit fields.
Can you give some example how to implement the Qt::EditDataRole to display also the % sign on edit?
Is it also necessary to implement setData to store the value on the DB without percent sign?
A lot of thanks,
Alex B.
A never implemented the setData before. Can you give me some example. I think it has to be somethink like this:
- if(!index.isValid())
- return false;
- if (index.column() == CUSTOMERS_DISCOUNT)
- {
- return ModelBase::setData(index, data, Qt::EditRole);
- }
- else
- return ModelBase::setData(index,value,role);
- }
but I’m to sure how to parse the imput string
Alex B.
That is basic string parsing. You could something like this (untested):
- //trim off white space
- valueString = valueString.trimmed(); //get rid of additional white space
- if (valueString.endsWith('%'))
- valueString.chop(1); //chop off % sign if we have one
- bool ok;
- double valueDbl = valueString.toDouble(&ok);
- if (!ok)
- return false; //value is not a number
- //if you mapped 0.2 to 20%, then you have to map the other way too:
- valueDbl /= 100.0;
- //set the value on the actual data store and return true
You must log in to post a reply. Not a member yet? Register here!


