Transferring an object in multiple formats

The big advantage of using wxPython data objects for data transfer is that the data objects are aware of their format. A data object can even manage the same data in multiple formats. For example, you may want your own application to receive your data in your own custom formatted text object, but you may still want other applications to be able to receive the data as plain text.

The mechanism for managing this functionality is the class wx.DataObject-Composite. All of the derived data objects we've seen so far have been subclasses of wx.DataObjectSimple. The purpose of wx.DataObjectComposite is to combine an arbitrary number of simple data objects into one data object. The combined object can deliver its data to a data object matching any of the component simple types.

To build a composite data object, start with the no-argument constructor wx.DataObjectComposite(), and then add the individual data simple objects with the method Add(data, preferred=False). To build a data object that combines your custom format with a plain text one, use.

data_object = wx.CustomDataObject("MyNiftyFormat") data_object.SetData(cPickle.dumps(my_object)) text_object = wx.TextDataObject(str(my_object)) composite = wx.DataObjectComposite() composite.Add(data_object) composite.Add(text_object)

After this, pass the composite object to the clipboard or your drop source. If the target class requests the data using a data object in the custom format, it receives the pickled object. If it requests the data as plain text, it gets the string representation. The Add() method takes a second argument, preferred, which is a Boolean that marks the particular data object as the default if the target object does not specify a format (or specifies more than one). If no component is explicitly marked as preferred, the first object added is considered to be the preferred one.

In the next section, we'll show you how to use a timer to manage regularly scheduled events.

Was this article helpful?

0 0

Post a comment