MEVIS3000 MEVIS3000 - 1 month ago 9
Python Question

PyQt4 table for inserting a table from the clipboard - tableWidget?

I am looking for a table that can be generated with the Qt Designer or directly with PyQt4, where one can insert a content, which was copied from an Excel spreadsheet.
So, for instance having someting like this in the clipboard:


1 5


2 2


3 2



And then paste it into something like this, such that every number is in a different cell:

enter image description here

I have the following code for that:

from PyQt4 import QtCore, QtGui
import sys


class Ui_MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)

def setupUi(self, MainWindow):
MainWindow.resize(320, 120)

self.centralwidget = QtGui.QWidget(MainWindow)
self.tableWidget = QtGui.QTableWidget(self.centralwidget)

self.tableWidget.setEnabled(True)
self.tableWidget.setGeometry(QtCore.QRect(0, 0, 400, 200))
self.tableWidget.setRowCount(3)
self.tableWidget.setColumnCount(3)

MainWindow.setCentralWidget(self.centralwidget)

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Ui_MainWindow()
ex.show()
sys.exit(app.exec_())


The problem now is that one has to chose every cell independently, and it is not possible to mark several cells with this widget.
Anyone having a suggestion for an alternative widget or an suitable adjustment of this widget?

Answer

You'll need to catch the Ctrl-V keyboard event by overriding the keyPressEvent method and processing the clipboard data manually.

class MyTable(QtGui.QTableWidget):

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_V and event.modifiers() == QtCore.Qt.ControlModifier:
            # Check to see if clipboard contains excel data.
            # Manually process clipboard data and insert 
            # it into the table starting from the selected tableitem
            ...
            return
        super(MyTable, self).keyPressEvent(event)

You can use QClipboard and QMimeData to get the excel data from the clipboard.

from pprint import pprint
clip = QtGui.QApplication.clipboard()
mime = clip.mimeData()
pprint(mime.formats())

You should see something like this:

[u'text/html',  
 u'text/plain', 
 u'application/x-qt-windows-mime;value="Csv"',  
 ...

That last one is the excel data. Excel will place the data in several different formats into the clipbaord, you can check each one to see which format you like best, but CSV is probably the simplest to deal with if you don't care about formatting.

data = mime.data('application/x-qt-windws-mime;value="Csv"')
# convert from QByteArray to python string
data = str(data.data())
print data

You should see the data you copied in csv format.

a,b,c
d,e,f

Then just parse the data and insert it into the table.

Comments