我不知道如何实现捕获鼠标对 wxListCtrl 列表中任何内容的点击。
分享如何在wxListCtrl中捕获点击的基本完整实现示例。
您可以在 Github 存储库中找到 listctrl 的示例https://github.com/wxWidgets/wxWidgets/tree/master/samples/listctrl
这是一个值得效仿的好例子。
在这里,我编写了一个最小的应用程序,其概念与鼠标左键单击和鼠标右键单击相同。
#include <wx/wx.h>
#include <wx/listctrl.h>
// Main frame class
class MyFrame : public wxFrame
{
public:
MyFrame();
private:
void OnListCtrlItemActivated(wxListEvent& event);
void OnListCtrlRightClick(wxListEvent& event);
wxListCtrl* listCtrl;
wxDECLARE_EVENT_TABLE();
};
// Event table
wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_LIST_ITEM_ACTIVATED(wxID_ANY, MyFrame::OnListCtrlItemActivated)
EVT_LIST_ITEM_RIGHT_CLICK(wxID_ANY, MyFrame::OnListCtrlRightClick)
wxEND_EVENT_TABLE()
// Application class
class MyApp : public wxApp
{
public:
virtual bool OnInit();
};
// Main frame implementation
MyFrame::MyFrame()
: wxFrame(NULL, wxID_ANY, "wxListCtrl Example", wxDefaultPosition, wxSize(600, 400))
{
// Create the list control
listCtrl = new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxLC_REPORT | wxLC_SINGLE_SEL);
// Add columns
listCtrl->InsertColumn(0, "ID", wxLIST_FORMAT_LEFT, 100);
listCtrl->InsertColumn(1, "Name", wxLIST_FORMAT_LEFT, 200);
listCtrl->InsertColumn(2, "Age", wxLIST_FORMAT_LEFT, 100);
// Add items
listCtrl->InsertItem(0, "1"); // First column
listCtrl->SetItem(0, 1, "Alice"); // Second column
listCtrl->SetItem(0, 2, "25"); // Third column
listCtrl->InsertItem(1, "2");
listCtrl->SetItem(1, 1, "Bob");
listCtrl->SetItem(1, 2, "30");
listCtrl->InsertItem(2, "3");
listCtrl->SetItem(2, 1, "Charlie");
listCtrl->SetItem(2, 2, "35");
// Use a sizer to ensure the list control expands to fill the frame
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(listCtrl, 1, wxEXPAND | wxALL, 5);
SetSizer(sizer);
}
// Event handler for item activation (double-click or Enter key)
void MyFrame::OnListCtrlItemActivated(wxListEvent& event)
{
long itemIndex = event.GetIndex();
wxString itemText = listCtrl->GetItemText(itemIndex);
wxLogMessage("Item activated: %s", itemText);
}
// Event handler for right-click on an item
void MyFrame::OnListCtrlRightClick(wxListEvent& event)
{
long itemIndex = event.GetIndex();
wxString itemText = listCtrl->GetItemText(itemIndex);
wxLogMessage("Right-clicked on item: %s", itemText);
}
// Main application implementation
bool MyApp::OnInit()
{
MyFrame* frame = new MyFrame();
frame->Show(true);
return true;
}
wxIMPLEMENT_APP(MyApp);