【发布时间】:2025-12-30 19:35:12
【问题描述】:
我想在我的应用程序中使用 wxTimer,但我不想使用预处理器宏来绑定事件。相反,我想在 CTOR 调用期间使用 Bind() 将事件绑定到我的 ui 元素。
绑定我的计时器后,它不启动或不调用事件处理程序。根据this,它应该像我想的那样工作。我也不想使用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;
}
【问题讨论】: