MEVIS3000 MEVIS3000 - 2 months ago 14
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):

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

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

self.tableWidget.setGeometry(QtCore.QRect(0, 0, 400, 200))


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

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?


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
        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()

You should see something like this:


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 ='application/x-qt-windws-mime;value="Csv"')
# convert from QByteArray to python string
data = str(
print data

You should see the data you copied in csv format.


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