wxpython 中 用鼠标拖动控件 总结

#encoding: utf-8
import wx
import os
import noname

class Frame( noname.MyFrame1 ):
    def __init__(self,parent):
        noname.MyFrame1.__init__(self,parent)
        self.curBitmap = None
        self.curBitmapPostion = None
        self.curPointerPos    = None
    def m_createBitmap_buttonOnButtonClick ( self,event ):
        event.Skip()
    def m_bitmap1OnLeftDown ( self,event ):
        self.curBitmapPostion = self.m_bitmap1.GetPosition()
        self.curPointerPos = event.GetPosition()
        event.Skip()
    def m_bitmap1OnMotion ( self,event ):
        if event.Dragging() and event.LeftIsDown() :
            pos = event.GetPosition() - self.curPointerPos
            self.curBitmapPostion += pos
            statusVal = 'X = %d   Y = %d' %(self.curBitmapPostion.x,self.curBitmapPostion.y)
            self.m_statusBar1.SetStatusText(statusVal)
            self.m_bitmap1.Move(self.curBitmapPostion)
        event.Skip()

 

实现的功能是在panel上创建一个staticBitmap,然后可以用鼠标在panel上任意随鼠标拖动staticBitmap。

实际上可以拖动任意控件。

思路:

监听staticBitmap(被拖动控件)的wx.EVT_MOTION,和wx.EVT_LEFT_DOWN 事件。

当鼠标左键在staticBitmap上按下是记录此刻:

1,鼠标的位置(event.GetPosition() 这是相对坐标,而且是相对监听控件的(这里监听它的是staticBitmap))。

2,staticBitmap(被拖动控件)的位置(staticBitmap的GetPosition() 返回的是控件左上角相对父控件的位置)。

鼠标的位置是用来计算偏移的,staticBitmap的位置加上这个偏移就是被拖动的位置。

调用staticBitmap的Move(Point),将控件移动到相对父控件的。

碰到的一些问题:

1,并不是所有的event,调用Skip() 后都传递给父控件。下面链接有解答。

http://stackoverflow.com/questions/11606068/about-event-skip,

2,一开始是监听panel的wx.EVT_MOTION,但是鼠标一放到staticBitmap上,panel就监听不到这个事件了。上面链接提到了

wx.PostEvent(staticBitmap(被拖动控件).GetParent(),event),本来想把事件post给panel,这样panel来计算鼠标偏移,这样更准确,不会有闪烁的情况。但是post成功了,但是panel里面触发了这个事件,但是event.GetPosition() 依然是相对staticBitmap(被拖动控件)的,而不是相对panel(父控件)的,虽然事件触发了。

 

posted @ 2014-01-10 15:12  lc_cnblog  阅读(2967)  评论(0编辑  收藏  举报