nim_duilib(3)之按鈕
阿新 • • 發佈:2020-12-10
introduction
lets go
xml檔案新增程式碼
下面的xml檔案內容,刪除label控制元件的相關程式碼,增加了3個按鈕。 其中,程式碼如下:
<?xml version="1.0" encoding="UTF-8"?> <Window size="600,400" caption="0,0,0,35"> <VBox bkcolor="bk_wnd_darkcolor"> <HBox width="stretch" height="35" bkcolor="bk_wnd_lightcolor"> <Control /> <Button class="btn_wnd_min" name="minbtn" margin="4,6,0,0" /> <Box width="21" margin="4,6,0,0"> <Button class="btn_wnd_max" name="maxbtn"/> <Button class="btn_wnd_restore" name="restorebtn" visible="false"/> </Box> <Button class="btn_wnd_close" name="closebtn" margin="4,6,8,0"/> </HBox> <!--下面是中間的控制元件--> <VBox padding="30, 30, 30, 30" > <HBox> <VBox> <!-- Buttons --> <Button class="btn_global_blue_80x30" name="btn_blue" text="blue" /> <Button class="btn_global_white_80x30" name="btn_white" text="white"/> <Button class="btn_global_red_80x30" name="btn_red" text="red"/> </VBox> </HBox> </VBox> <!--下面是中間的控制元件 結束--> </VBox> </Window>
其中新增的程式碼用註釋括起來了。
解釋
上述的xml程式碼中,整體是垂直佈局,其中,窗體中間是用的是垂直佈局,為了繼續增加控制元件,又套了一個水平佈局,按鈕使用的是垂直佈局。 class屬性需要到global.xml檔案中檢視。
回到VS專案中
開啟 BasicForm.h, 類中新增下面的程式碼, 用於與上面的按鈕關聯。
private:
// 定義了3個buttons
ui::Button *pbtn_arr_[3];
同時增加一個函式,用於處理按鈕點選事件
private: // // @ brief: 按鈕點選事件 // @ str_name - 顯示內容 // @ return - void void OnCenterBtnClick(const std::wstring &&str_name);
開啟BasicForm.cpp, 新增下面的程式碼到InitWindow函式中。
// 查詢介面的按鈕 pbtn_arr_[0] = dynamic_cast<ui::Button*>(FindControl(L"btn_blue")); pbtn_arr_[1] = dynamic_cast<ui::Button*>(FindControl(L"btn_white")); pbtn_arr_[2] = dynamic_cast<ui::Button*>(FindControl(L"btn_red")); // 為按鈕繫結觸發點選的事件 for (unsigned int index = 0; index < 3; ++index) { pbtn_arr_[index]->AttachClick([this](ui::EventArgs* args) { OnCenterBtnClick(args->pSender->GetName() + std::wstring(L"\n")); return true; }); }
其中,btn_blue為xml中的name屬性。使用lambda表示式,呼叫函式上面新增的函式OnCenterBtnClick。而OnCenterBtnClick的函式體如下:
//
// @brief:
//
void BasicForm::OnCenterBtnClick(const std::wstring &&str_name)
{
LPCWSTR result = str_name.c_str();
OutputDebugString(result);
}
點選按鈕
執行除錯,點選按鈕,VS2017的輸出視窗中將輸出點選按鈕的名字。例如:
至此,我們已經能夠點選按鈕並處理按鈕的點選。