我想在我的应用程序中使用wxTimer,但我不想使用预处理宏来绑定事件。相反,我希望在CTOR调用期间使用
绑定计时器后,它没有启动或者没有调用事件处理程序。根据此处的描述,它应该按照我想要的方式工作。我也不想使用
Bind()
将事件绑定到我的UI元素上。绑定计时器后,它没有启动或者没有调用事件处理程序。根据此处的描述,它应该按照我想要的方式工作。我也不想使用
Connect()
。以同样的方式绑定按钮就可以正常工作。这是一个最小的示例:#include <wx/wx.h>
#include <iostream>
class MainFrame : public wxFrame
{
private:
const int DELTA_TIME = 100; // time between timer events (in ms)
private:
wxTimer* timer = nullptr;
void OnTimer(wxTimerEvent& evt);
void OnButtonClick(wxCommandEvent& evt);
public:
MainFrame();
virtual ~MainFrame();
};
void MainFrame::OnTimer(wxTimerEvent& evt)
{
std::cout << "Timer Event!" << std::endl; // never happens
}
void MainFrame::OnButtonClick(wxCommandEvent& evt)
{
std::cout << "Button Event!" << std::endl; // works just fine
}
MainFrame::MainFrame()
: wxFrame(nullptr, wxID_ANY, "Test", wxPoint(0, 0), wxSize(600, 400))
{
timer = new wxTimer(this, wxID_ANY);
timer->Bind(
wxEVT_TIMER, // evt type
&MainFrame::OnTimer, // callback
this, // parent
timer->GetId() // id
);
timer->Start(DELTA_TIME, wxTIMER_CONTINUOUS);
wxButton* testBtn = new wxButton(this, wxID_ANY, "Test", wxPoint(20, 20));
testBtn->Bind(wxEVT_BUTTON, &MainFrame::OnButtonClick, this);
}
MainFrame::~MainFrame()
{
if (timer->IsRunning())
{
timer->Stop();
}
}
// application class
class Main : public wxApp
{
public:
virtual bool OnInit();
};
IMPLEMENT_APP(Main)
bool Main::OnInit()
{
MainFrame* mainFrame = new MainFrame();
SetTopWindow(mainFrame);
mainFrame->Show();
return true;
}
testBtn->Bind(wxEVT_BUTTON
这行代码是正确的。按钮和其他控件没有像计时器那样的所有者类似物。事件直接抛给它们。因此,testBtn->Bind(wxEVT_BUTTON,...
这行代码将指向this
对象的MainFrame
类的OnButtonClick
方法设置为处理特定按钮的 wxEVT_BUTTON 类型事件的方法。由于这些事件在单击按钮时被抛出,它们将由该方法处理。 - New PagodiBind(wxEVT_BUTTON,&MainFrame::OnButtonClick,this,testBtn->GetId(),testBtn->GetId());
在这种情况下,这意味着主框架应该通过调用OnButtonClick方法来处理类型为wxEVT_BUTTON并且事件ID为testBtn的事件。 - New PagoditestBtn->Bind(wxEVT_BUTTON,...
)中,我们不需要id,因为按钮应该只接收自己点击产生的wxEVT_BUTTON类型事件。因此,使用一个方法处理所有这样的事件是合理的。然而,当使用主框架来处理wxEVT_BUTTON事件时,如果我们不提供ids(即仅使用Bind(wxEVT_BUTTON,&MainFrame::OnButtonClick,this);
),它将使用该方法来处理所有按钮点击事件。 - New Pagodi