C++,wxWidgets实现3个按钮,每个按钮点击wxbitmap按钮,更换按钮图标,并且互斥,完整显示示例
时间: 2024-03-09 21:48:35 浏览: 99
好的,这是一个基于wxWidgets的C++程序,实现了3个按钮,点击每个按钮后会更换按钮图标,实现互斥,完整显示示例如下:
```c++
#include <wx/wx.h>
class MyFrame : public wxFrame {
public:
MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
private:
void OnButton1(wxCommandEvent& event);
void OnButton2(wxCommandEvent& event);
void OnButton3(wxCommandEvent& event);
wxBitmapButton* m_button1;
wxBitmapButton* m_button2;
wxBitmapButton* m_button3;
wxBitmap m_bitmap1;
wxBitmap m_bitmap2;
wxBitmap m_bitmap3;
wxDECLARE_EVENT_TABLE();
};
wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_BUTTON(wxID_ANY, MyFrame::OnButton1)
EVT_BUTTON(wxID_ANY, MyFrame::OnButton2)
EVT_BUTTON(wxID_ANY, MyFrame::OnButton3)
wxEND_EVENT_TABLE()
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame(NULL, wxID_ANY, title, pos, size)
{
// Load bitmaps
m_bitmap1.LoadFile(wxT("button1.bmp"), wxBITMAP_TYPE_BMP);
m_bitmap2.LoadFile(wxT("button2.bmp"), wxBITMAP_TYPE_BMP);
m_bitmap3.LoadFile(wxT("button3.bmp"), wxBITMAP_TYPE_BMP);
// Create buttons
m_button1 = new wxBitmapButton(this, wxID_ANY, m_bitmap1, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW);
m_button2 = new wxBitmapButton(this, wxID_ANY, m_bitmap2, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW);
m_button3 = new wxBitmapButton(this, wxID_ANY, m_bitmap3, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW);
// Set initial state
m_button1->SetBackgroundColour(wxColour(255, 0, 0));
m_button2->SetBackgroundColour(wxColour(0, 255, 0));
m_button3->SetBackgroundColour(wxColour(0, 0, 255));
// Create sizers
wxBoxSizer* sizer1 = new wxBoxSizer(wxHORIZONTAL);
sizer1->Add(m_button1, 1, wxEXPAND | wxALL, 5);
sizer1->Add(m_button2, 1, wxEXPAND | wxALL, 5);
sizer1->Add(m_button3, 1, wxEXPAND | wxALL, 5);
wxBoxSizer* sizer2 = new wxBoxSizer(wxVERTICAL);
sizer2->Add(sizer1, 1, wxEXPAND | wxALL, 5);
SetSizerAndFit(sizer2);
}
void MyFrame::OnButton1(wxCommandEvent& event)
{
m_button1->SetBitmap(m_bitmap2);
m_button2->SetBitmap(m_bitmap1);
m_button3->SetBitmap(m_bitmap1);
}
void MyFrame::OnButton2(wxCommandEvent& event)
{
m_button1->SetBitmap(m_bitmap1);
m_button2->SetBitmap(m_bitmap3);
m_button3->SetBitmap(m_bitmap1);
}
void MyFrame::OnButton3(wxCommandEvent& event)
{
m_button1->SetBitmap(m_bitmap1);
m_button2->SetBitmap(m_bitmap1);
m_button3->SetBitmap(m_bitmap2);
}
class MyApp : public wxApp {
public:
virtual bool OnInit();
};
bool MyApp::OnInit()
{
MyFrame* frame = new MyFrame(wxT("Button Example"), wxDefaultPosition, wxSize(300, 200));
frame->Show(true);
return true;
}
wxIMPLEMENT_APP(MyApp);
```
程序中使用了`wxBitmapButton`控件来创建按钮,并且在按钮单击事件中使用`SetBitmap`方法来更换按钮图标。同时,使用颜色来区分不同的按钮,实现互斥效果。
程序中使用了3个位图文件作为按钮图标,分别命名为`button1.bmp`、`button2.bmp`、`button3.bmp`,需要放在程序同一目录下。
程序运行后,会创建一个窗口,其中包含3个按钮。点击每个按钮,会更换按钮图标,并且其他按钮的图标会恢复为原始状态。
阅读全文