Search code examples
c++wxwidgets

Adding my own Icon for wxAuiToolBar


I want to add a button to an wxAuiToolBar that shows an icon that I created myself (I have it as the file myicon.png with resolution 24x24).

The best I manged so far is to convert to bmp-file and use the following code for wxsmith:

<wxsmith>
    <object class="wxFrame" name="MyFrame">
        <size>800,640</size>
        <object class="wxAuiManager" variable="aui_manager" member="yes">
            <object class="AuiManagerItem">
                <object class="wxAuiToolBar" name="ID_AUITOOLBAR" variable="toolbar" member="yes">
                    <pos>90,3</pos>
                    <object class="AuiToolBarItem">
                        <object class="wxAuiToolBarItem" name="ID_AUITOOLBARMEASURE" variable="AuiToolBarMeasure" member="yes">
                            <bitmap>/home/username/project/icon.bmp</bitmap>
                            <handler function="OnTest" entry="EVT_TOOL" />
                        </object>
                        <label>Test</label>
                    </object>
                </object>
            </object>
        </object>
    </object>
</wxsmith>

Leading to the following source code:

toolbar->AddTool(ID_AUITOOLBAR1, _("Test"),
    wxBitmap(wxImage(_T("/home/username/project/icon.bmp"))), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString, NULL);

However the transparency information is lost.

If I use the png-file or convert to xpm then I get a runtime error: "../src/gtk/bitmap.cpp(626): assert "image.IsOk()" failed in wxBitmap(): invalid image"

Currently I'm trying to get it working with WxSmith, but if that turns out not to be possible I'd also be happy if anyone can help me to get it working without.


Solution

  • In order to load PNG files during run-time you need to register the PNG image handler which can be done with wxInitAllImageHandlers(). And you still should actually check that bitmap creation succeeded because it's always possible that the file wasn't found or corrupted.

    Alternatively, you can embed PNG directly in your program and then use the convenient wxBITMAP_PNG() macro to load it. In this case you can usually omit the error handling.