I'm trying to create some kind of canvas for my project but got a behaviour that I cannot tell why, so I decided to prepare a minimal test case with the advise of a user at the IRC.
Here, I create a scrolled window inside a wxFrame. I try to draw some lines on it which should appear at exactly the same point even when the user is scrolling. But the case is that drawing messes up when scrolling, much like when you don't use DoPrepareDC().
Here is the -1 file- code:
Code: Select all
// main.cpp
#include <cstdio>
#include <wx/wx.h>
// Headers
class MyApp: public wxApp
{
public:
virtual bool OnInit();
};
class GUI: public wxFrame
{
public:
GUI();
};
class Canvas: public wxScrolledWindow
{
public:
Canvas(wxFrame *parent);
void OnPaint(wxPaintEvent& paint_event);
void OnSize(wxSizeEvent& size_event);
private:
DECLARE_EVENT_TABLE()
int default_unit_width;
};
// Definitions
IMPLEMENT_APP(MyApp)
BEGIN_EVENT_TABLE(Canvas, wxScrolledWindow)
EVT_PAINT(Canvas::OnPaint)
EVT_SIZE(Canvas::OnSize)
END_EVENT_TABLE()
Canvas::Canvas(wxFrame *parent): wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize)
{
this->default_unit_width = 10;
SetScrollbars(this->default_unit_width, this->default_unit_width, 1000, 1000);
}
void Canvas::OnPaint(wxPaintEvent& paint_event)
{
wxPaintDC canvas(this);
DoPrepareDC(canvas);
int x = 0;
int y = 0;
this->GetViewStart(&x, &y);
printf("%d\n", x);
canvas.DrawLine(x * this->default_unit_width + 100, 30, x * this->default_unit_width + 200, 70);
canvas.DrawLine(x * this->default_unit_width + 500, 100, x * this->default_unit_width + 300, 200);
}
void Canvas::OnSize(wxSizeEvent& size_event)
{
Refresh();
}
GUI::GUI(): wxFrame(NULL, wxID_ANY, wxT("Example"), wxDefaultPosition, wxSize(500, 350))
{
wxBoxSizer *box_sizer_main = new wxBoxSizer(wxHORIZONTAL);
Canvas *canvas_main = new Canvas(this);
box_sizer_main->Add(canvas_main, 1, wxEXPAND);
SetSizer(box_sizer_main);
Centre();
}
bool MyApp::OnInit()
{
GUI *gui = new GUI();
gui->Show(true);
return true;
}
The interesting thing is that when I comment out the this->GetViewStart(&x, &y); line it works right but of course then it does not draw the lines at the same place when the user scrolls.
I put printf("%d\n", x); line so that you can see the values of x or y variables, which seem fine to me.
Another observation: After it messes up the drawings, if you resize the window, you see that they are drawn correctly.
I am on Ubuntu 9.04 with wxWidgets 2.8.9.1.
I'm new to both wxWidgets and C++ so maybe it might be pretty easy to solve, sorry if it is a very easy problem