[PyQt] QWindowsMime

Anthony Heading aheading at jpmorgan.com
Tue Sep 18 15:02:23 BST 2007


On Tue, Sep 18, 2007 at 09:29:44AM +0100, Phil Thompson wrote:
> The Qt4 version has a different API that uses Windows types that aren't 
> wrapped. It may be possible to wrap a useful subset - but I'm not qualified 
> to define "useful". What exactly would need to be implemented to give you 
> what you need?

Thanks.  My main use is putting data onto the clipboard with slightly
specialized Windows types.

Attached below is a principal example: the pyqt3 code we are using to
send data to Microsoft Office in CSV format.  

Worth highlighting that Qt3 didn't provide quite enough to get the job
done either, we additionally needed to hook up to the win32 API
RegisterClipboardFormat function, as you see below.  So it's not great
problem for us if we have to code it all up in C instead, but hopefully
this provides one example of "useful"...

Regards

Anthony

=====================

from qt import *
import sys

from my_own_win32_api_library import RegisterClipboardFormat

class WindowsMimeCSV(QWindowsMime):
    def __init__(self, *args):
	QWindowsMime.__init__(self)
	self.cfnum = RegisterClipboardFormat("Csv");
	
    def canConvert(self, mime, cf):
	return mime == "text/csv" and cf == self.cfnum
	
    def cf(self, pos):
	return self.cfnum
    
    def cfFor(self, mime):
	if mime == "text/csv":
	    return self.cfnum
	return 0

    def convertFromMime(self, data, mime, cf):
	return str(data)
    
    def convertToMime(self, data, mine, cf):
	return str(data)
    
    def convertorName(self):
	return "Csv"
    
    def countCf(self):
	return 1
    
    def mimeFor(self, cf):
	if cf == self.cfnum:
	    return "text/csv"
	return None

_WindowsMimeCSV = None
_QClipboard = None

def RegisterCSV():
    global _WindowsMimeCSV, _QClipboard
    if _WindowsMimeCSV is None:
	_WindowsMimeCSV = WindowsMimeCSV()
    if _QClipboard is None:
	_QClipboard = QApplication.clipboard()

class CSVMimeSource(QMimeSource):
    def __init__(self, data):
	QMimeSource.__init__(self)
	RegisterCSV()
	self.data = data
    
    def encodedData(self, mime):
	lines = []
	for row in self.data:
	    fields = []
	    for field in row:
		x = str(field)
		if "," in x: x = '"%s"' % x
		fields.append(x)
	    lines.append(",".join(fields))
	csv = "\n".join(lines)
	return csv
    
    def format(self, i):
	if i == 0:
	    return "text/csv"
	return None
    
    def provides(self, mime):
	if mime == "text/csv":
	    return true
	return false

def CSVExport(data):
    mimeSource = CSVMimeSource (data)
    clipboard  = QApplication.clipboard()
    clipboard.setData (mimeSource, QClipboard.Clipboard)

if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    
    x = CSVExport([[1,2],[3,4],[99,104]])

    app.exec_loop()


More information about the PyQt mailing list