Search code examples
c++wxwidgets

ID_BUTTON was not initialized with constant expression


I would like to use the "Enter" and "Shift" keys in my application. To accomplish that, I found some code here.

void wxWidgetsDialog::OnKey(wxKeyEvent &event)
{
  wxWindow *win = FindFocus();
  if(win == NULL){
     event.Skip ();
     return;
  }

  if(event.GetKeyCode()==WXK_RETURN){
      switch(win->GetId()){
     case ID_BUTTON1:
           wxMessageBox("Button1");
           break;
      case ID_BUTTON2:
           wxMessageBox("Button2");
           break;
      case ID_BUTTON3:
           wxMessageBox("Button3");
          Destroy();
           break;                    
   }
   event.Skip ();
  }

}

When I try to use this snippet, I get the errors:

D:\WindowsDgps\WindowsDgpsGUI\PortsDialog.cpp|171|error: the value of 'PortsDialog::ID_BUTTON1' is not usable in a constant expression|

and

D:\WindowsDgps\WindowsDgpsGUI\PortsDialog.cpp|35|note: 'PortsDialog::ID_BUTTON1' was not initialized with a constant expression|

What did I do wrong? How do I have to declare the IDs to make this work? I used the standard implementation wxWidgets generates itself.

const long PortsDialog::ID_STATICTEXT1 = wxNewId();
const long PortsDialog::ID_TEXTCTRL1 = wxNewId();
const long PortsDialog::ID_BUTTON1 = wxNewId();
const long PortsDialog::ID_TEXTCTRL2 = wxNewId();
const long PortsDialog::ID_BUTTON2 = wxNewId();
const long PortsDialog::ID_BUTTON3 = wxNewId();
const long PortsDialog::ID_PANEL1 = wxNewId();

Is there anything I can do, so that I can use the Enter key to activate a Button while I am in a StaticText field?


Solution

  • While PortsDialog::ID_BUTTON1 is constant in the way that you can't change it, it's not a compile-time constant. The value of it isn't fixed at compilation, it's initialized at run-time.

    The cases in a switch must be compile-time constants.

    You can't use switch here, but have to use an if and else if chain.