为了让按钮可以拓展功能,除了点击,还想支持拖拽,把包含的信息给到其他的控件使用,该类的设计如下:
class DropButton(wx.lib.buttons.GenBitmapButton):
def __init__(self, parent, bitmap, Tip, data):
wx.lib.buttons.GenBitmapButton.__init__(self, parent, bitmap=bitmap,size=wx.Size(28, 28), style=wx.NO_BORDER)
self.SetToolTipString(Tip)
self.Bind(wx.EVT_LEFT_DOWN, self.on_button_down)
self.Bind(wx.EVT_LEFT_UP, self.on_button_up)
self.Bind(wx.EVT_MOTION, self.on_motion)
self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.on_capture_lost)
self.data = data
self.DefaultColour = self.GetBackgroundColour()
self.prePostion = None
self.IsDowning = False
def SetData(self, data):
self.data = data
def ClearData(self):
self.data = None
def on_motion(self, event):
if self.prePostion != None and self.IsDowning == True:
position = event.GetPosition()
if position[0]-self.prePostion[0] > 0 or position[1]-self.prePostion[1] >0:
if self.data != None:
self.IsDowning = False
wx.CallLater(100, self.do_drag_drop)
event.Skip()
def do_drag_drop(self):
data = wx.TextDataObject(str(self.data))
dragSource = wx.DropSource(self)
dragSource.SetData(data)
dragSource.DoDragDrop()
def on_button_down(self, event):
self.IsDowning = True
self.prePostion = event.GetPosition()
event.Skip()
def on_button_up(self, event):
self.IsDowning = False
event.Skip()
"""
注意没有该事件会出现:C++ assertion "Assert failure" failed at ..\..\src\common\wincmn.cpp(3346)
in DoNotifyWindowAboutCaptureLost():
window that captured the mouse didn't process wxEVT_MOUSE_CAPTURE_LOST
"""
def on_capture_lost(self, event):
# 鼠标捕获丢失事件处理
pass
这里的思路是不移动鼠标则不设置拖拽功能,直接使用正常点击功能,如果按下出现了鼠标的移动,则需要设置拖拽的内容,注意这里要使用wx.CallLater,防止出现按下的按钮不会回弹,这是因为DoDraoDrop是阻塞的,会影响按钮的显示效果。
最后的capture_lost只是为了处理使用中出现的一个报错。