Transferring a custom data object

Although the available data object options of text, bitmap, and list of filenames are flexible enough to cover a variety of uses, sometimes you will need to transfer a custom object, such as your own graphic format, or a custom data structure. Next, we'll cover a mechanism for transferring custom data objects, while retaining control over what kind of data your object will accept. The limitation on this method is that, for reasons that will be abundantly clear in a moment, it only works within wxPython. You cannot use this method to allow other applications to read your custom format. To send RTF to Microsoft Word, this mechanism won't work.

To do the custom data transfer, we're going to use the wxPython class wx.Cus-tomDataObject, which is designed to handle arbitrary data. The constructor for wx.CustomDataObject is.


The format parameter is technically an instance of the class wx.DataFormat, however, for our purposes, we can just pass it a string, and wxPython will take care of the data type. We only need the string to act as a label to differentiate one custom format from another. Once we have our custom data instance, we can put data into it using the method SetData(data). The catch here is that in wxPython, the data parameter has to be a string. An annoying limitation, but there's a Python process for converting almost any Python object into a string—the pickle module. So, the boilerplate code will look something like this.

data_object = wx.CustomDataObject("MyNiftyFormat") data = cPickle.dumps(my_object) data_object.SetData(data)

After this snippet, you can pass the data_object to the clipboard or another data source to continue the data transfer.

Was this article helpful?

0 0

Post a comment