wxPython中按钮支持拖拽和点击功能

该文章介绍了一个自定义的GenBitmapButton类,它扩展了点击和拖拽功能。当按钮被按下且鼠标移动时,触发拖拽操作,通过wx.CallLater避免DoDragDrop导致的按钮显示问题。同时,文章提到了一个C++的assertion错误,该错误在鼠标捕获丢失时发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为了让按钮可以拓展功能,除了点击,还想支持拖拽,把包含的信息给到其他的控件使用,该类的设计如下: 

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只是为了处理使用中出现的一个报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值