例子
在以下示例中,两个 ListCrl 对象水平放置在 Box Sizer 中。左侧的列表填充了语言[] 数据。它被指定为阻力源。右边一个是目标。
languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP', 'VB.NET','C#']
self.lst1 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
self.lst2 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
for lang in languages:
self.lst1.InsertStringItem(0,lang)
第二个列表控件为空,是 TextDropTarget 类的对象的参数。
class MyTextDropTarget(wx.TextDropTarget):
def __init__(self, object):
wx.TextDropTarget.__init__(self)
self.object = object
def OnDropText(self, x, y, data):
self.object.InsertStringItem(0, data)
OnDropText() 方法在目标列表控件中添加源数据。
拖动操作由事件绑定器初始化。
wx.EVT_LIST_BEGIN_DRAG(self, self.lst1.GetId(), self.OnDragInit)
OnDragInit() 函数将拖动数据放在目标上并从源中删除。
def OnDragInit(self, event):
text = self.lst1.GetItemText(event.GetIndex())
tobj = wx.PyTextDataObject(text)
src = wx.DropSource(self.lst1)
src.SetData(tobj)
src.DoDragDrop(True)
self.lst1.DeleteItem(event.GetIndex())
完整的代码如下 -
import wx
class MyTarget(wx.TextDropTarget):
def __init__(self, object):
wx.TextDropTarget.__init__(self)
self.object = object
def OnDropText(self, x, y, data):
self.object.InsertStringItem(0, data)
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title = title,size = (-1,300))
panel = wx.Panel(self)
box = wx.BoxSizer(wx.HORIZONTAL)
languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript',
'PHP', 'VB.NET','C#']
self.lst1 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
self.lst2 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
for lang in languages:
self.lst1.InsertStringItem(0,lang)
dt = MyTarget(self.lst2)
self.lst2.SetDropTarget(dt)
wx.EVT_LIST_BEGIN_DRAG(self, self.lst1.GetId(), self.OnDragInit)
box.Add(self.lst1,0,wx.EXPAND)
box.Add(self.lst2, 1, wx.EXPAND)
panel.SetSizer(box)
panel.Fit()
self.Centre()
self.Show(True)
def OnDragInit(self, event):
text = self.lst1.GetItemText(event.GetIndex())
tobj = wx.PyTextDataObject(text)
src = wx.DropSource(self.lst1)
src.SetData(tobj)
src.DoDragDrop(True)
self.lst1.DeleteItem(event.GetIndex())
ex = wx.App()
Mywin(None,'Drag&Drop Demo')
ex.MainLoop()
上面的代码产生以下输出 -