Merged TableWidget updates from Laugher

This commit is contained in:
Luke Campagnola 2013-03-06 05:43:02 -05:00
commit 916face815

View File

@ -6,7 +6,7 @@ import numpy as np
try: try:
import metaarray import metaarray
HAVE_METAARRAY = True HAVE_METAARRAY = True
except: except ImportError:
HAVE_METAARRAY = False HAVE_METAARRAY = False
__all__ = ['TableWidget'] __all__ = ['TableWidget']
@ -26,6 +26,8 @@ class TableWidget(QtGui.QTableWidget):
QtGui.QTableWidget.__init__(self, *args) QtGui.QTableWidget.__init__(self, *args)
self.setVerticalScrollMode(self.ScrollPerPixel) self.setVerticalScrollMode(self.ScrollPerPixel)
self.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection) self.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
self.setSortingEnabled(True)
self.clear() self.clear()
self.contextMenu = QtGui.QMenu() self.contextMenu = QtGui.QMenu()
self.contextMenu.addAction('Copy Selection').triggered.connect(self.copySel) self.contextMenu.addAction('Copy Selection').triggered.connect(self.copySel)
@ -44,6 +46,7 @@ class TableWidget(QtGui.QTableWidget):
def setData(self, data): def setData(self, data):
self.clear() self.clear()
self.appendData(data) self.appendData(data)
self.resizeColumnsToContents()
def appendData(self, data): def appendData(self, data):
"""Types allowed: """Types allowed:
@ -60,26 +63,19 @@ class TableWidget(QtGui.QTableWidget):
first = next(it0) first = next(it0)
except StopIteration: except StopIteration:
return return
#if type(first) == type(np.float64(1)):
# return
fn1, header1 = self.iteratorFn(first) fn1, header1 = self.iteratorFn(first)
if fn1 is None: if fn1 is None:
self.clear() self.clear()
return return
#print fn0, header0
#print fn1, header1
firstVals = [x for x in fn1(first)] firstVals = [x for x in fn1(first)]
self.setColumnCount(len(firstVals)) self.setColumnCount(len(firstVals))
#print header0, header1
if not self.verticalHeadersSet and header0 is not None: if not self.verticalHeadersSet and header0 is not None:
#print "set header 0:", header0
self.setRowCount(len(header0)) self.setRowCount(len(header0))
self.setVerticalHeaderLabels(header0) self.setVerticalHeaderLabels(header0)
self.verticalHeadersSet = True self.verticalHeadersSet = True
if not self.horizontalHeadersSet and header1 is not None: if not self.horizontalHeadersSet and header1 is not None:
#print "set header 1:", header1
self.setHorizontalHeaderLabels(header1) self.setHorizontalHeaderLabels(header1)
self.horizontalHeadersSet = True self.horizontalHeadersSet = True
@ -110,13 +106,16 @@ class TableWidget(QtGui.QTableWidget):
elif data is None: elif data is None:
return (None,None) return (None,None)
else: else:
raise Exception("Don't know how to iterate over data type: %s" % str(type(data))) msg = "Don't know how to iterate over data type: {!s}".format(type(data))
raise TypeError(msg)
def iterFirstAxis(self, data): def iterFirstAxis(self, data):
for i in range(data.shape[0]): for i in range(data.shape[0]):
yield data[i] yield data[i]
def iterate(self, data): ## for numpy.void, which can be iterated but mysteriously has no __iter__ (??) def iterate(self, data):
# for numpy.void, which can be iterated but mysteriously
# has no __iter__ (??)
for x in data: for x in data:
yield x yield x
@ -124,14 +123,13 @@ class TableWidget(QtGui.QTableWidget):
self.appendData([data]) self.appendData([data])
def addRow(self, vals): def addRow(self, vals):
#print "add row:", vals
row = self.rowCount() row = self.rowCount()
self.setRowCount(row+1) self.setRowCount(row + 1)
self.setRow(row, vals) self.setRow(row, vals)
def setRow(self, row, vals): def setRow(self, row, vals):
if row > self.rowCount()-1: if row > self.rowCount() - 1:
self.setRowCount(row+1) self.setRowCount(row + 1)
for col in range(self.columnCount()): for col in range(self.columnCount()):
val = vals[col] val = vals[col]
if isinstance(val, float) or isinstance(val, np.floating): if isinstance(val, float) or isinstance(val, np.floating):
@ -140,16 +138,31 @@ class TableWidget(QtGui.QTableWidget):
s = str(val) s = str(val)
item = QtGui.QTableWidgetItem(s) item = QtGui.QTableWidgetItem(s)
item.value = val item.value = val
#print "add item to row %d:"%row, item, item.value # by default this is enabled, selectable & editable, but
# we don't want editable
item.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
self.items.append(item) self.items.append(item)
self.setItem(row, col, item) self.setItem(row, col, item)
def sizeHint(self):
# based on http://stackoverflow.com/a/7195443/54056
width = sum(self.columnWidth(i) for i in range(self.columnCount()))
width += self.verticalHeader().sizeHint().width()
width += self.verticalScrollBar().sizeHint().width()
width += self.frameWidth() * 2
height = sum(self.rowHeight(i) for i in range(self.rowCount()))
height += self.verticalHeader().sizeHint().height()
height += self.horizontalScrollBar().sizeHint().height()
return QtCore.QSize(width, height)
def serialize(self, useSelection=False): def serialize(self, useSelection=False):
"""Convert entire table (or just selected area) into tab-separated text values""" """Convert entire table (or just selected area) into tab-separated text values"""
if useSelection: if useSelection:
selection = self.selectedRanges()[0] selection = self.selectedRanges()[0]
rows = list(range(selection.topRow(), selection.bottomRow()+1)) rows = list(range(selection.topRow(),
columns = list(range(selection.leftColumn(), selection.rightColumn()+1)) selection.bottomRow() + 1))
columns = list(range(selection.leftColumn(),
selection.rightColumn() + 1))
else: else:
rows = list(range(self.rowCount())) rows = list(range(self.rowCount()))
columns = list(range(self.columnCount())) columns = list(range(self.columnCount()))