Skip to content

Instantly share code, notes, and snippets.

@lighth7015
Created March 24, 2020 13:34
Show Gist options
  • Save lighth7015/0b6744b8dba9c516b41511ca42f14754 to your computer and use it in GitHub Desktop.
Save lighth7015/0b6744b8dba9c516b41511ca42f14754 to your computer and use it in GitHub Desktop.
wxwidgets drag child
#include <wx/wx.h>
#include <wx/utils.h>
template <class T>
class Movable : public T {
bool dragging;
int x,y;
int height, width;
int top, left, topScreen, leftScreen;
wxWindow* parent;
void updateCursorPos(wxMouseEvent& evt) {
wxPoint mouseOnScreen = wxGetMousePosition();
int nx = mouseOnScreen.x - x,
ny = mouseOnScreen.y - y;
wxPoint position(parent->ScreenToClient(wxPoint( nx, ny )));
this->Move(position);
}
protected:
/*
* Attach the event handler manually
*/
void ConnectEvents() {
this->Connect(wxEVT_LEFT_DOWN, wxMouseEventHandler(Movable<T>::onMouseDown));
this->Connect(wxEVT_LEFT_UP, wxMouseEventHandler(Movable<T>::onMouseUp));
this->Connect(wxEVT_MOTION, wxMouseEventHandler(Movable<T>::onMove));
}
public:
/*
* Constructor
*/
Movable(wxWindow* parent) : T (parent, wxID_ANY, wxT("Drag me around")) {
Movable::parent = parent;
ConnectEvents();
dragging = false;
}
/*
* Mouse button press
*/
void onMouseDown(wxMouseEvent& evt) {
this->CaptureMouse();
x = evt.GetX();
y = evt.GetY();
parent->GetScreenPosition(&topScreen, &leftScreen);
dragging=true;
}
/*
* Mouse button release
*/
void onMouseUp(wxMouseEvent& evt) {
this->ReleaseMouse();
dragging=false;
}
/*
* Mouse cursor motion
*/
void onMove(wxMouseEvent& evt)
{
//int newHeight, newWidth;
wxPoint mouseOnScreen = this->ScreenToClient(wxGetMousePosition());
this->GetSize(&height, &width);
this->GetScreenPosition(&top, &left);
/*
* Are we supposed to be dragging our widget around the container?
*/
if (dragging) {
wxSetCursor( wxNullCursor );
updateCursorPos( evt );
}
else {
this->SetLabel(wxString::Format("%d %d %d %d", mouseOnScreen.x, height, mouseOnScreen.y, width));
// Change cursor to signify that pointer is on border
auto cursor = wxNullCursor;
if ((( mouseOnScreen.x > 0 && mouseOnScreen.y > 0 ))
&& ((( mouseOnScreen.x < height && mouseOnScreen.y < width )))) {
// Do nothing.
}
else if (mouseOnScreen.x == 0) {
cursor = wxCURSOR_SIZEWE;
}
else if (mouseOnScreen.y == 0) {
cursor = wxCURSOR_SIZENS;
}
::wxSetCursor( cursor );
}
}
};
class MyFrame : public wxFrame {
wxPanel* mainPanel = new wxPanel(this, wxID_ANY);
Movable<wxButton> *btnMove1 = new Movable<wxButton>(this);
public:
MyFrame(wxWindow* ptr, int id, wxString name, wxPoint pos, wxSize size) : wxFrame(ptr,id,name,pos,size) {
Center();
Show();
}
};
class Application: public wxApp {
MyFrame* frame = new MyFrame(NULL, wxID_ANY, wxT("Hello World"), wxDefaultPosition, wxSize(640,480));
virtual bool OnInit();
};
IMPLEMENT_APP(Application)
bool Application::OnInit() {
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment