Search code examples
c++wxwidgets

wxGauge was nullptr out of constructor


first of all sorry for my english, its not my first language

i'm beginner on wxWidgets for c++ and i started to developer a simple application with a progress bar and some background process

unfortunately when i call wx_MyGauge->SetValue(20), a exception "wx_MyGauge was nullptr" occurs

this only occurs outside the constructor, if i call that function from constructor, works perfectly

what am i doing wrong?

//header

#pragma once
#include "wx/wx.h"

class testGauge : public wxFrame
{
public:
    testGauge();
    ~testGauge();

    wxGauge* wx_MyGauge;
    wxPanel* pnl;

    void Importar(wxMouseEvent& event);
};

//cpp

#include "testGauge.h"
testGauge::testGauge() : wxFrame(nullptr, wxID_ANY, "blabla", wxDefaultPosition, wxSize(500, 400))
{
    pnl = new wxPanel(this, wxID_ANY, wxPoint(10, 10), wxSize(500, 400));

    wx_MyGauge= new wxGauge(pnl, 1001, 100, wxPoint(10,10), wxSize(100,20), wxGA_HORIZONTAL);
    wx_MyGauge->SetValue(10);// here OK

    wxButton* btn = new wxButton(pnl,wxID_ANY,"Teste",wxPoint(10,30),wxSize(50,30));
    btn->Connect(wxEVT_LEFT_UP, wxMouseEventHandler(testGauge::Importar));
    

    this->Layout();
    this->Centre(wxBOTH);
}


void testGauge::Importar(wxMouseEvent& WXUNUSED(event))
{
    testGauge::wx_MyGauge->SetValue(20);// here Error 
}

testGauge::~testGauge()
{

}

working on windows 10, visual studio 2019, wxWidgets 3.1.5

imageerror


Solution

  • You call the method Connect of the pnl and don't pass which event handler Importar is. Thus, the method Connect joins the mouse event to pnl instead of testGuage

    btn->Connect(wxEVT_LEFT_UP, wxMouseEventHandler(testGauge::Importar));
    

    Must be

    btn->Connect(wxEVT_LEFT_UP, wxMouseEventHandler(testGauge::Importar), nullptr, this);