问题
I have created a simple app which uses bare TextCtrl widgets with wxFILTER_NUMERIC in order to accept only numerical values (see code below).
I want the values to have a fixed display precision irrespective of how user inputs them (e.g. will always show 17.0000 in case of 17.0 or 17.000000 values being specified). I found that in wxPython there is an option to use a derived NumCtrl widget (http://wxpython.org/docs/api/wx.lib.masked.numctrl-module.html) which does the job but I can't find it in the basic wxWidgets libraries.
So, is there a ready solution for this available somewhere which I simply cannot find or do I have to write a function which will change the format of the number manually once it has been inserted (handling EVT_TEXT and EVT_TEXT_ENTER events and modifying the input string)?
What I have so far:
Event table
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(ID_Quit, MyFrame::OnQuit)
EVT_MENU(ID_About, MyFrame::OnAbout)
EVT_TEXT(ID_textBox, MyFrame::ValueChanged)
EVT_TEXT_ENTER(ID_textBox, MyFrame::ValueChanged)
END_EVENT_TABLE()
Implementation of the text box inside MyFrame
wxPanel *panel = new wxPanel(this, -1);
_textBox1 = new wxTextCtrl(panel,
ID_textBox,
"0.0000",
wxPoint(100, 100),
wxSize(80,20),
wxTE_PROCESS_ENTER,
wxTextValidator(wxFILTER_NUMERIC,&_myValue),
wxTextCtrlNameStr);
Handling function
void MyFrame::ValueChanged(wxCommandEvent& WXUNUSED(event))
{
// modify the string or do something clever
}
SOLUTION ADOPTED Thanks to the answer the problem has been resolved. Here's what I went with:
`
wxFloatingPointValidator<double> _val(2,&_myValue,wxNUM_VAL_ZERO_AS_BLANK);
_val.SetRange(0.,100.); // set allowable range
_textBox1 = new wxTextCtrl(panel, // create a textCtrl
ID_textBox,
"0.0000",
wxPoint(100, 30),
wxSize(80,20),
wxTE_PROCESS_ENTER,
_val, // associate the text box with the desired validator
wxTextCtrlNameStr);
`
回答1:
See wxFloatingPointValidator available in wxWidgets 2.9.
来源:https://stackoverflow.com/questions/14428727/formatting-wx-textctrl-with-numeric-values-only-float-precision