PDA

View Full Version : (PyQt) User dictated row arrangment?



jkrienert
14th January 2015, 15:33
Hello.
WorkFlow:
[QAbstractTableModel]<===>[QtableView]

Vertical Header is moveable, and when the user enacts such functionality, the following is called (from QtableView):


self.tableView.verticalHeader().setMovable(True)
self.tableView.verticalHeader().sectionMoved.conne ct(self.rowsChanged)
...

def rowsChanged(self,dataRow,oldDisplayRow,newDisplayR ow):
self.tableData.resortRows(dataRow,oldDisplayRow,ne wDisplayRow)

QAbstractTableModel catches the call, and enacts the following:


def resortRows(self,dataRow,oldDisplayRow,newDisplayRo w):
print "you moved dataRow %s from displayRow %s to displayRow %s" % (dataRow,oldDisplayRow,newDisplayRow)
self.rows.insert(newDisplayRow,self.rows.pop(dataR ow))
self.layoutChanged.emit()

While the underlying data structure (self.rows) is properly rearranged, the QtableView does not reflect these changes - and rather exhibits random offsetting of rows; non-synchronous with the ACTUAL changes made.




Are the 'beginInsertRows(...)/endInstertRows()' and 'beginRemoveRows(...)/endRemoveRows()' nessecary?
As when I implement these as follows, neither the QtableView, nor the underlying data (self.rows) is properly altered:

def resortRows(self,dataRow,oldDisplayRow,newDisplayRo w):
print "you moved dataRow %s from displayRow %s to displayRow %s" % (dataRow,oldDisplayRow,newDisplayRow)
self.beginInsertRows(QtCore.QModelIndex(),newDispl ayRow,newDisplayRow)
self.rows.insert(newDisplayRow,self.rows[dataRow])
self.endInsertRows()
self.beginRemoveRows(QtCore.QModelIndex(),dataRow, dataRow)
self.rows.pop(dataRow)
self.endRemoveRows()

A billion thanks!

Added after 23 minutes:

Doh!

Not yet sure if this is the most elegant manner, but implementing the following in QAbstractModel solved the problems (for now):



def resortRows(self,dataRow,oldDisplayRow,newDisplayRo w):
print "you moved dataRow %s from displayRow %s to displayRow %s" % (dataRow,oldDisplayRow,newDisplayRow)
cacheData = self.rows[dataRow]
self.removeRows(dataRow)
self.beginInsertRows(QtCore.QModelIndex(),newDispl ayRow,newDisplayRow)
self.rows.insert(newDisplayRow,cacheData)
self.endInsertRows()

# removes row from model (only if entire row-children are selected)
def removeRows(self, row):
self.beginRemoveRows(QtCore.QModelIndex(),row,row)
self.rows.pop(int(row))
self.endRemoveRows()