UserPreferences

DailyNotes/2005/11/14/ClipboardAndCustomDataInWxPython


I've not been able to create a custom wx.DataObject that I can put and get off the wx.Clipboard.

Here's my sample code:

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
# scripts to test out whether I can put a custom data type on the clipboard and read it back in wx.Python

import wx

class MyDataObjectFormat(wx.DataFormat):
    def __init__(self):
        wx.DataFormat.__init__(self,0)
        wx.DataFormat.SetId(self,'MyDOFormat')

class MyDataObject(wx.PyDataObjectSimple):
    """
    taken from http://www.wxpython.org/docs/api/wx.PyDataObjectSimple-class.html
    """
    def __init__(self):
        wx.PyDataObjectSimple.__init__(
            self, wx.CustomDataFormat('MyDOFormat'))
        self.data = ''

    def GetDataSize(self):
        return len(self.data)
    def GetDataHere(self):
        return self.data  # returns a string  
    def SetData(self, data):
        self.data = data
        return True

myobj = MyDataObject()
myobj.SetData(u'hello')
print myobj.GetDataHere()

# put it on the clipboard and try to read it back

cb = wx.TheClipboard
if cb.Open():
    cb.SetData(myobj)
    cb.Close()

# now try to open and retrieve the clipboard object

if cb.Open():
    myobj2 = MyDataObject()
    if cb.IsSupported(MyDataObjectFormat()):
        print 'clipboard does support MyDataObject Format'
        if cb.GetData(myobj2):
            print 'reading from clipboard: ', myobj2.GetDataHere()
        else:
            print 'read from clipboard failed'
    cb.Close()

The output from the program is on my machine (wxPython 2.6.1.0 on WinXP):

>>> hello
clipboard does support MyDataObject Format
read from clipboard failed

I'm puzzled by what else I need to do to enable the clipboard to interact properly with MyDataObject.