生活随笔
收集整理的這篇文章主要介紹了
wxWidgets学习 (2) -- 事件处理
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
wxWidgets控件處理事件的傳統(tǒng)方法是使用事件表,2.9.0版本后新增了動態(tài)綁定方式。
這個小程序包含兩個按鈕(wxButton)和一個文本框(wxStaticText)。兩個按鈕采用不同的方式處理點(diǎn)擊事件,第一個按鈕采用靜態(tài)事件表,第二個按鈕采用動態(tài)綁定,點(diǎn)擊按鈕,按鈕計數(shù)值增加;文本框負(fù)責(zé)打印當(dāng)前窗口的寬高,采用動態(tài)綁定,輸出隨著窗口大小改變。
// C++11編譯
#include <wx/wx.h>class MyApp : public wxApp {
public:virtual bool OnInit();
};class MyFrame : public wxFrame {
public: MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size);private: wxButton* button1 = nullptr;wxButton* button2 = nullptr;wxStaticText *text = nullptr;void OnButton_1(wxCommandEvent&);void OnButton_2(wxCommandEvent&);void OnSize(wxSizeEvent &event);wxDECLARE_EVENT_TABLE(); // 聲明靜態(tài)事件表建議放在類的尾部,因?yàn)檫@個宏改變了可見性
};// 唯一的控件ID
enum {ID_BUTTON_1 = 1, ID_BUTTON_2, ID_TEXT
};// 按鈕1使用靜態(tài)事件表綁定點(diǎn)擊事件
wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)EVT_BUTTON(ID_BUTTON_1, MyFrame::OnButton_1)
wxEND_EVENT_TABLE()// 啟動程序
wxIMPLEMENT_APP(MyApp);// 成員函數(shù)實(shí)現(xiàn)
bool MyApp::OnInit() {// 創(chuàng)建 MyFrame 窗口,設(shè)置標(biāo)題,窗口位置,窗口大小MyFrame *frame = new MyFrame("Demo", wxPoint(50,50), wxSize(450, 340));frame->Show(true); // 顯示窗口return true; // 返回true表示繼續(xù)進(jìn)程,false表示立即終止程序
}MyFrame::MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size): wxFrame(nullptr, wxID_ANY, title, pos, size) {SetBackgroundColour("#339933"); // 修改frame背景顏色為綠色button1 = new wxButton(this, ID_BUTTON_1, "static event table:0");button2 = new wxButton(this, ID_BUTTON_2, "dynamic bind:0");text = new wxStaticText(this, ID_TEXT, "");button2->SetPosition({0, 50});text->SetPosition({0, 100});button2->Bind(wxEVT_BUTTON, &MyFrame::OnButton_2, this); // 按鈕2動態(tài)綁定點(diǎn)擊事件Bind(wxEVT_SIZE, &MyFrame::OnSize, this); // 動態(tài)綁定frame大小修改事件
}void MyFrame::OnButton_1(wxCommandEvent&) {static int cnt = 0;button1->SetLabel(wxString::Format("static event table:%d", ++cnt));
}void MyFrame::OnButton_2(wxCommandEvent&) {static int cnt = 0;button2->SetLabel(wxString::Format("dynamic bind:%d", ++cnt));
}void MyFrame::OnSize(wxSizeEvent &event) {wxSize size = event.GetSize();text->SetLabel(wxString::Format("width:%d\nheight:%d",size.GetWidth(),size.GetHeight()));
}
總結(jié)
以上是生活随笔為你收集整理的wxWidgets学习 (2) -- 事件处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。