nim_duilib(3)之按鈕


introduction

  • 更多控件用法,請參考 here 和 源碼。
  • 本文的代碼基於這里

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 OnCenterBtnClicked(const std::wstring &&str_name);

打開BasicForm.cpp, 新增下面的代碼到InitWindow函數中。

//
//	@brief: 
// 
void BasicForm::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_demo"));

	//  方法1: 綁定按鈕點擊事件 
	if (pbtn_arr_[0])
		pbtn_arr_[0]->AttachClick(nbase::Bind(&BasicForm::OnBtnClicked, this, std::placeholders::_1));

	 // 方法1: 為按鈕綁定觸發點擊的事件
	for (unsigned int index = 1; index < 3; ++index)
	{
		if (pbtn_arr_[index])
		{
			pbtn_arr_[index]->AttachClick([this](ui::EventArgs* args)
			{
				OnCenterBtnClicked(args->pSender->GetName() + std::wstring(L"\n"));
				return true;
			});
		}
	}
}

其中,btn_blue為xml中的name屬性。使用lambda表達式,調用函數上面新增的函數OnCenterBtnClicked。而OnCenterBtnClicked的函數體如下:

//
//	@brief: 
// 
void BasicForm::OnCenterBtnClicked(const std::wstring &&str_name) 
{
	LPCWSTR result = str_name.c_str();
	OutputDebugString(result);
}

點擊按鈕

運行調試,點擊按鈕,VS2017的輸出窗口中將輸出點擊按鈕的名字。例如:

至此,我們已經能夠點擊按鈕並處理按鈕的點擊。

其他

  • 按鈕控件Button有AttachMouseEnter、AttachButtonDown、AttachClick方法,他們分別用於指定控件鼠標進入、鼠標按下、鼠標單擊的事件處理函數。這些函數的具體用法,可以參考官方給出的例子。
  • EventArgs結構體中包含了觸發事件的控件的指針、鼠標坐標、按鍵狀態、時間戳等信息。函數的返回值,返回true表示繼續傳遞控件消息,返回false表示停止傳遞控件消息。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM