For hours I’ve been trying to learn how to use wxListBox from wxWidgets. I’ve based my “application” on official tutorial but I can’t get it working even though my code is not that different from original.
I want to add a new item to wxListBox but instead I get Segmentation fault. Here’s my code:
class CWindow : public wxFrame {
wxBoxSizer *hbox, *vbox;
wxListBox *list;
wxButton *btnAdd, *btnRemove;
public:
CWindow(int w = 640, int h = 480) : wxFrame(NULL, -1, wxT("Test"), wxDefaultPosition, wxSize(w, h)) {
list = new wxListBox(this, wxID_ANY, wxDefaultPosition, wxSize(w-100, h));
btnAdd = new wxButton(this, -1, wxT("Add"));
btnAdd->Connect(wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction) &CWindow::OnNew);
btnRemove = new wxButton(this, -1, wxT("Remove"));
vbox = new wxBoxSizer(wxVERTICAL);
vbox->Add(btnAdd, 1, wxALL | wxEXPAND, 0);
vbox->Add(btnRemove, 1, 0, 0);
hbox = new wxBoxSizer(wxHORIZONTAL);
hbox->Add(list, 1, 0, 0);
hbox->Add(vbox, 0, 0, 0);
SetSizer(hbox);
}
void OnNew(wxCommandEvent &event) {
wxString str = wxGetTextFromUser(wxT("New item:"));
if (str.Len() > 0) list->InsertItems(1, &str, 0); //this line is suspected of causing segfault
}
};
Any ideas what’s causing my issue?
PS. The tutorial example works just fine so library bug is not a possibility.
EDIT:
gdb debugger reports this:
0x00007ffff7a8e492 in wxListBoxBase::InsertItems(unsigned int, wxString const*, unsigned int) () from /usr/lib/x86_64-linux-gnu/libwx_gtk2u_core-2.8.so.0
EDIT2: more gdb dumps
Before:
Breakpoint 1, CWindow::OnNew (this=0x725cd0, event=...) at listbox.cpp:32
32 if (str.Len() > 0) list->InsertItems(1, &str, 0);
(gdb) print list
warning: can't find linker symbol for virtual table for `CWindow' value
$1 = (wxListBox *) 0x0
(gdb) up
#1 0x00007ffff7586d35 in wxEvtHandler::ProcessEventIfMatches(wxEventTableEntryBase const&, wxEvtHandler*, wxEvent&) ()
from /usr/lib/x86_64-linux-gnu/libwx_baseu-2.8.so.0
Thanks to many pieces of advice I was able to successfully resolve the issue. It was caused by directly connecting buttons to functions. It seems that each button must have a corresponding identifier.
So this is wrong:
And this is good: