FLTK 重写Fl_Button回调

这篇博客展示了如何通过重写FLTK的handle()函数来实现多个回调事件。作者创建了一个Button类,该类扩展了Fl_Button,并为FL_PUSH、FL_RELEASE、FL_MOVE、FL_HIDE和FL_SHOW事件定义了不同的回调函数。在主函数中,为按钮设置了不同事件的回调,改变按钮的标签以显示事件类型。
摘要由CSDN通过智能技术生成

众所周知,FLTK的回调只能有一个,其他的需要重写handle(),所以我打算直接重写handle(),制作多个回调

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
void no_cb(Fl_Widget*,void*){}
class Button : public Fl_Button
{
	private:
	void (*onPush)(Fl_Widget*,void*);
	void (*onRelease)(Fl_Widget*,void*);
	void (*onMove)(Fl_Widget*,void*);
	void (*onHide)(Fl_Widget*,void*);
	void (*onShow)(Fl_Widget*,void*);
	void* _push_data;
	void* _release_data;
	void* _move_data;
	void* _hide_data;
	void* _show_data;
	public:
	Button(int x,int y,int w,int h,char* l = 0)
	:Fl_Button(x,y,w,h,l)
	{
		onPush = no_cb;
		_push_data = 0;
		onRelease = no_cb;
		_release_data = 0;
		onMove = no_cb;
		_move_data = 0;
		onHide = no_cb;
		_hide_data = 0;
		onShow = no_cb;
		_show_data = 0;
	}
	int handle(int event)
	{
		switch(event)
		{
			case FL_PUSH:
			(*onPush)(this,_push_data);
			return 1;
			case FL_RELEASE:
			(*onRelease)(this,_release_data);
			return 1;
			case FL_MOVE:
			(*onMove)(this,_move_data);
			return 1;
			case FL_HIDE:
			(*onHide)(this,_hide_data);
			return 1;
			case FL_SHOW:
			(*onShow)(this,_show_data);
			return 1;
		}
		return 0;
	}
	void callback(int event,void (*cb)(Fl_Widget*,void*),void* data = 0)
	{
		switch(event)
		{
			case FL_PUSH:
			onPush = cb;
			_push_data = data;
			break;
			case FL_RELEASE:
			onRelease = cb;
			_release_data = data;
			break;
			case FL_MOVE:
			onMove = cb;
			_move_data = data;
			break;
			case FL_HIDE:
			onHide = cb;
			_hide_data = data;
			break;
			case FL_SHOW:
			onShow = cb;
			_show_data = data;
			break;
			
		}
	}
};
int main()
{
	Fl_Window window(600,800,"");
	Button btn(0,0,600,100);
	btn.callback(FL_PUSH,[](Fl_Widget* w,void*)
	{
		((Button*)(w))->label("push");
	});
	btn.callback(FL_RELEASE,[](Fl_Widget* w,void*)
	{
		((Button*)(w))->label("release");
	});
	btn.callback(FL_MOVE,[](Fl_Widget* w,void*)
	{
		((Button*)(w))->label("move");
	});
	btn.callback(FL_HIDE,[](Fl_Widget* w,void*)
	{
		((Button*)(w))->label("hide");
	});
	btn.callback(FL_SHOW,[](Fl_Widget* w,void*)
	{
		((Button*)(w))->label("show");
	});
	window.show();
	return Fl::run();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值