I want to draw some text when click a button. My code is:
#include <wx/wx.h>
enum
{
BUTTON_Hello = wxID_HIGHEST + 1
};
class myFrame : public wxFrame {
public:
wxButton* HelloWorld;
wxPanel* panel;
void OnPaint(wxCommandEvent& event) {
wxClientDC bdc =wxClientDC(this);
bdc.DrawText(wxString("Draw some text when button clicked."), wxPoint(300, 300));
Refresh();
};
myFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize) :
wxFrame(parent,id,title, pos, size) {
panel =new wxPanel(this, wxID_ANY, wxPoint(0,0),wxSize(100,100));
//Connect(wxEVT_PAINT, wxPaintEventHandler(myFrame::OnPaint));
HelloWorld = new wxButton(panel, BUTTON_Hello, _T("Hello World"),
wxPoint(5,5), wxSize(100, 100));
HelloWorld->Bind(wxEVT_BUTTON, &myFrame::OnPaint, this);
};
};
class MyApp : public wxApp
{
bool OnInit() {
frame = new myFrame((wxFrame*)NULL, -1, wxT("Hello wxDC"),
wxPoint(50, 50), wxSize(800, 600));
frame->Show();
return true;
};
wxFrame* frame;
public:
};
IMPLEMENT_APP(MyApp)
I define the drawing function in a wxFrame
and bind it to a wxButton
using Bind()
. The drawing function uses a wxClientDC
. I have added Refersh()
to force updating wxFrame
. The wxButton
belongs to a wxPanel
which is a child of wxFrame
.
However, when I click the button, nothing happens and no text is shown.
You must use wxPaintDC
when drawing in your wxEVT_PAINT
handler, not wxClientDC
. While wxClientDC
also "works", at least for now and at least under some platforms, this is definitely not the right way to do it.
When using wxPaintDC
, Refresh()
would work as expected and will result in a call to your paint handler during the next event loop iteration. Normally you don't need to call Update()
, which immediately calls your handler, at all.