1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
|
#------------------------------------------------------------------------------
# Copyright (c) 2008, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms described
# in the PyQt GPL exception also apply.
#
# Author: Riverbank Computing Limited
#------------------------------------------------------------------------------
""" Defines the table model used by the table editor.
"""
#-------------------------------------------------------------------------------
# Imports:
#-------------------------------------------------------------------------------
from pyface.qt import QtCore, QtGui
from traitsui.ui_traits import SequenceTypes
#-------------------------------------------------------------------------------
# Constants:
#-------------------------------------------------------------------------------
# Mapping for trait alignment values to qt4 horizontal alignment constants
h_alignment_map = {
'left': QtCore.Qt.AlignLeft,
'center': QtCore.Qt.AlignHCenter,
'right': QtCore.Qt.AlignRight,
}
# Mapping for trait alignment values to qt4 vertical alignment constants
v_alignment_map = {
'top': QtCore.Qt.AlignTop,
'center': QtCore.Qt.AlignVCenter,
'bottom': QtCore.Qt.AlignBottom,
}
# MIME type for internal table drag/drop operations
mime_type = 'traits-ui-table-editor'
def as_qcolor(color):
""" Convert a color specification (maybe a tuple) into a QColor.
"""
if isinstance(color, SequenceTypes):
return QtGui.QColor(*color)
else:
return QtGui.QColor(color)
#-------------------------------------------------------------------------------
# 'TableModel' class:
#-------------------------------------------------------------------------------
class TableModel(QtCore.QAbstractTableModel):
"""The model for table data."""
def __init__(self, editor, parent=None):
"""Initialise the object."""
QtCore.QAbstractTableModel.__init__(self, parent)
self._editor = editor
#---------------------------------------------------------------------------
# QAbstractTableModel interface:
#---------------------------------------------------------------------------
def rowCount(self, mi):
"""Reimplemented to return the number of rows."""
return len(self._editor.items())
def columnCount(self, mi):
"""Reimplemented to return the number of columns."""
return len(self._editor.columns)
def data(self, mi, role):
"""Reimplemented to return the data."""
obj = self._editor.items()[mi.row()]
column = self._editor.columns[mi.column()]
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
text = column.get_value(obj)
if text is not None:
return text
elif role == QtCore.Qt.ToolTipRole:
tooltip = column.get_tooltip(obj)
if tooltip:
return tooltip
elif role == QtCore.Qt.FontRole:
font = column.get_text_font(obj)
if font is not None:
return QtGui.QFont(font)
elif role == QtCore.Qt.TextAlignmentRole:
string = column.get_horizontal_alignment(obj)
h_alignment = h_alignment_map.get(string, QtCore.Qt.AlignLeft)
string = column.get_vertical_alignment(obj)
v_alignment = v_alignment_map.get(string, QtCore.Qt.AlignVCenter)
return (h_alignment | v_alignment)
elif role == QtCore.Qt.BackgroundRole:
color = column.get_cell_color(obj)
if color is None:
# FIXME: Yes, this is weird. It should work fine to fall through
# to the catch-all None at the end, but it doesn't.
return None
else:
q_color = as_qcolor(color)
return QtGui.QBrush(q_color)
elif role == QtCore.Qt.ForegroundRole:
color = column.get_text_color(obj)
if color is not None:
q_color = as_qcolor(color)
return QtGui.QBrush(q_color)
elif role == QtCore.Qt.UserRole:
return obj
elif role == QtCore.Qt.CheckStateRole:
if column.get_type(obj) == "bool" and column.show_checkbox:
if column.get_raw_value(obj):
return QtCore.Qt.Checked
else:
return QtCore.Qt.Unchecked
return None
def flags(self, mi):
"""Reimplemented to set editable and movable status."""
flags = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled
if not mi.isValid():
return flags
editor = self._editor
obj = editor.items()[mi.row()]
column = editor.columns[mi.column()]
if editor.factory.editable and column.is_editable(obj):
flags |= QtCore.Qt.ItemIsEditable
if editor.factory.reorderable:
flags |= QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled
if column.get_type(obj) == "bool" and column.show_checkbox:
flags |= QtCore.Qt.ItemIsUserCheckable
return flags
def headerData(self, section, orientation, role):
"""Reimplemented to return the header data."""
if orientation == QtCore.Qt.Horizontal:
editor = self._editor
column = editor.columns[section]
if role == QtCore.Qt.DisplayRole:
return column.get_label()
elif orientation == QtCore.Qt.Vertical:
if role == QtCore.Qt.DisplayRole:
return str(section + 1)
return None
def insertRow(self, row, parent=QtCore.QModelIndex(), obj=None):
"""Reimplemented to allow creation of new rows. Added an optional
arg to allow the insertion of an existing row object."""
editor = self._editor
if obj is None:
obj = editor.create_new_row()
self.beginInsertRows(parent, row, row)
editor.callx(editor.items().insert, row, obj)
self.endInsertRows()
return True
def insertRows(self, row, count, parent=QtCore.QModelIndex()):
"""Reimplemented to allow creation of new rows."""
editor = self._editor
items = editor.items()
self.beginInsertRows(parent, row, row + count - 1)
for i in xrange(count):
editor.callx(items.insert, row + i, editor.create_new_row())
self.endInsertRows()
return True
def removeRows(self, row, count, parent=QtCore.QModelIndex()):
"""Reimplemented to allow row deletion, as well as reordering via drag
and drop."""
editor = self._editor
items = editor.items()
self.beginRemoveRows(parent, row, row + count - 1)
for i in xrange(count):
editor.callx(items.pop, row + i)
self.endRemoveRows()
return True
def mimeTypes(self):
"""Reimplemented to expose our internal MIME type for drag and drop
operations."""
types = QtCore.QStringList()
types.append(mime_type)
return types
def mimeData(self, indexes):
"""Reimplemented to generate MIME data containing the rows of the
current selection."""
mime_data = QtCore.QMimeData()
rows = list(set([ index.row() for index in indexes ]))
data = QtCore.QByteArray(str(rows[0]))
for row in rows[1:]:
data.append(' %i' % row)
mime_data.setData(mime_type, data)
return mime_data
def dropMimeData(self, mime_data, action, row, column, parent):
"""Reimplemented to allow items to be moved."""
if action == QtCore.Qt.IgnoreAction:
return False
data = mime_data.data(mime_type)
if data.isNull():
return False
current_rows = map(int, str(data).split(' '))
self.moveRows(current_rows, parent.row())
return True
def supportedDropActions(self):
"""Reimplemented to allow items to be moved."""
return QtCore.Qt.MoveAction
#---------------------------------------------------------------------------
# TableModel interface:
#---------------------------------------------------------------------------
def moveRow(self, old_row, new_row):
"""Convenience method to move a single row."""
return self.moveRows([old_row], new_row)
def moveRows(self, current_rows, new_row):
"""Moves a sequence of rows (provided as a list of row indexes) to a new
row."""
# Sort rows in descending order so they can be removed without
# invalidating the indices.
current_rows.sort()
current_rows.reverse()
# If the the highest selected row is lower than the destination, do an
# insertion before rather than after the destination.
if current_rows[-1] < new_row:
new_row += 1
# Remove selected rows...
items = self._editor.items()
objects = []
for row in current_rows:
if row <= new_row:
new_row -= 1
objects.insert(0, items[row])
self.removeRow(row)
# ...and add them at the new location.
for i, obj in enumerate(objects):
self.insertRow(new_row + i, obj=obj)
# Update the selection for the new location.
self._editor.set_selection(objects)
#-------------------------------------------------------------------------------
# 'SortFilterTableModel' class:
#-------------------------------------------------------------------------------
class SortFilterTableModel(QtGui.QSortFilterProxyModel):
"""A wrapper for the TableModel which provides sorting and filtering
capability."""
def __init__(self, editor, parent=None):
"""Initialise the object."""
QtGui.QSortFilterProxyModel.__init__(self, parent)
self._editor = editor
#---------------------------------------------------------------------------
# QSortFilterProxyModel interface:
#---------------------------------------------------------------------------
def filterAcceptsRow(self, source_row, source_parent):
""""Reimplemented to use a TableFilter for filtering rows."""
if self._editor._filtered_cache is None:
return True
else:
return self._editor._filtered_cache[source_row]
def filterAcceptsColumn(self, source_column, source_parent):
"""Reimplemented to save time, because we always return True."""
return True
def lessThan(self, left_mi, right_mi):
"""Reimplemented to sort according to the 'cmp' method defined for
TableColumn."""
editor = self._editor
column = editor.columns[left_mi.column()]
items = editor.items()
left, right = items[left_mi.row()], items[right_mi.row()]
return column.cmp(left, right) < 0
#---------------------------------------------------------------------------
# SortFilterTableModel interface:
#---------------------------------------------------------------------------
def moveRow(self, old_row, new_row):
"""Convenience method to move a single row."""
return self.moveRows([old_row], new_row)
def moveRows(self, current_rows, new_row):
"""Delegate to source model with mapped rows."""
source = self.sourceModel()
current_rows = [ self.mapToSource(self.index(row, 0)).row()
for row in current_rows ]
new_row = self.mapToSource(self.index(new_row, 0)).row()
source.moveRows(current_rows, new_row)
|