How to avoid drop on node - python

In my QtreeViewI use a 'QStandardItemModel` for displaying several items with individual properties. I want to avoid that the item will not be mixed. e.g. Bananas should be moveable to vegetables (same child level) but not below Asia (higher level), moving to Asia - Fruits is ok (same child level)
Sample
I've worked with .itemChanged but it appears to late. I need a signal before it will be dropped and the item where it will be dropped. I tried eventFilterand get
event.type() == QtCore.QEvent.DragMove:
but how do I get the index of the item where the item will be dropped to decide it its in the same child level?

To solve this problem I have created a custom mimetype that sends the information of the index and the level of depth that it has, and it will only move those indexes that have the same level as the children of the destination.
class TreeView(QTreeView):
customMimeType = "application/x-customqstandarditemmodeldatalist"
def __init__(self, *args, **kwargs):
QTreeView.__init__(self, *args, **kwargs)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setDragEnabled(True)
self.viewport().setAcceptDrops(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(QTreeView.InternalMove)
def itemsToPixmap(self, indexes):
rect = self.viewport().visibleRegion().boundingRect()
pixmap = QPixmap(rect.size())
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
for index in indexes:
painter.drawPixmap(self.visualRect(index), self.viewport().grab(self.visualRect(index)))
return pixmap
def mimeTypes(self):
mimetypes = QTreeView.mimeTypes(self)
mimetypes.append(TreeView.customMimeType)
return mimetypes
def startDrag(self, supportedActions):
drag = QDrag(self)
mimedata = self.model().mimeData(self.selectedIndexes())
encoded = QByteArray()
stream = QDataStream(encoded, QIODevice.WriteOnly)
self.encodeData(self.selectedIndexes(), stream)
mimedata.setData(TreeView.customMimeType, encoded)
drag.setMimeData(mimedata)
px = self.itemsToPixmap(self.selectedIndexes())
drag.setPixmap(px)
drag.setHotSpot(self.viewport().mapFromGlobal(QCursor.pos()) - QPoint(self.horizontalOffset(),
self.verticalOffset()))
drag.exec_(supportedActions)
def encodeData(self, items, stream):
stream.writeInt32(len(items))
for item in items:
p = item
rows = []
while p.isValid():
rows.append(p.row())
p = p.parent()
stream.writeInt32(len(rows))
for row in reversed(rows):
stream.writeInt32(row)
def dropEvent(self, event):
if event.source() == self:
if event.mimeData().hasFormat(TreeView.customMimeType):
encoded = event.mimeData().data(TreeView.customMimeType)
items = self.decodeData(encoded, event.source())
ix = self.indexAt(event.pos())
current = self.model().itemFromIndex(ix)
p = current
level = 1
while p:
p = p.parent()
level += 1
for item, ilevel in items:
if level == ilevel:
item.parent().takeRow(item.row())
current.appendRow(item)
self.clearSelection()
event.acceptProposedAction()
else:
event.ignore()
def decodeData(self, encoded, tree):
items = []
rows = []
stream = QDataStream(encoded, QIODevice.ReadOnly)
while not stream.atEnd():
nItems = stream.readInt32()
for i in range(nItems):
path = stream.readInt32()
row = []
for j in range(path):
row.append(stream.readInt32())
rows.append(row)
for row in rows:
it = self.model().item(row[0])
for r in row[1:]:
it = it.child(r)
items.append((it, len(row)))
return items
A complete example can be found in the following link

The following changes allow to move an item inside a row of childs, but not outside. Still working for changing the cursor if target is not the same level.
def dropEvent(self, event):
if event.source() == self:
if event.mimeData().hasFormat(TreeView.customMimeType):
encoded = event.mimeData().data(TreeView.customMimeType)
items = self.decodeData(encoded, event.source())
ix = self.indexAt(event.pos())
current = self.model().itemFromIndex(ix)
p = current
level = 0
while p:
p = p.parent()
level += 1
for item, ilevel in items:
if level == ilevel:
item.parent().takeRow(item.row())
current.parent().insertRow(current.row(),item)
self.clearSelection()
event.acceptProposedAction()
else:
event.ignore()

Related

How to save selected Items to Qsettings from QListWidget, QTableWidget

I am Using PyQt5 and Py3.7, I am trying to loop through all my Qlistwidgets and save their string data, but also save all selected items on that widget. I slightly modified the loop from here, but am having some trouble getting the selected items to save and restore using the listwidget array loop. I checked the docs but can't seem to understand how to add additional options into the array (such as save all selected items), from the Qt docs for SetArrayIndex, here.
My listWidgets have selectionMode set to MultiSelection.
I am currently saving using this:
def save_list_data(self):
self.settings = QSettings("data.ini", QSettings.IniFormat)
for name, obj in inspect.getmembers(self):
if isinstance(obj, QListWidget):
name = obj.objectName()
self.settings.beginWriteArray(name)
for i in range(obj.count()):
self.settings.setArrayIndex(i)
self.settings.setValue(name, obj.item(i).text())
self.settings.endArray()
And then restoring the listWidget data using:
def open_list_data(self):
self.settings = QSettings("data.ini", QSettings.IniFormat)
for name, obj in inspect.getmembers(self):
if isinstance(obj, QListWidget):
name = obj.objectName()
size = self.settings.beginReadArray(name)
for i in range(size):
self.settings.setArrayIndex(i)
value = self.settings.value(name)
if value != None:
obj.addItem(value)
self.settings.endArray()
This works fine for the data, but how can I get the selectedItems from the ListWidgets to save and restore as well?
For my solution take into account the following:
Using the inspect module may be beneficial for other libraries, but for Qt the widget is not necessarily a member of the class so it is best to use the Qt introspection itself using findChildren.
In the example you use, you are only saving the text but a QListWidgetItem can have more information associated with the roles such as background color, foreground color, etc. So instead I will use the QDataStream operator since this take and save takes the item information.
I will use the "objectname/property" format to save the information since the same widget can have several properties that you want to save.
To save the information of the selected items, it is only necessary to save the row.
Considering the above, the solution is:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.listwidget_1 = QtWidgets.QListWidget(
objectName="listwidget_1",
selectionMode=QtWidgets.QAbstractItemView.MultiSelection
)
listwidget_2 = QtWidgets.QListWidget(
objectName="listwidget_2",
selectionMode=QtWidgets.QAbstractItemView.MultiSelection
)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.listwidget_1)
lay.addWidget(listwidget_2)
self.read_settings()
def closeEvent(self, event):
self.write_settings()
super().closeEvent(event)
def read_settings(self):
settings = QtCore.QSettings("data.ini", QtCore.QSettings.IniFormat)
childrens = self.findChildren(QtWidgets.QWidget)
for children in childrens:
if isinstance(children, QtWidgets.QListWidget) and children.objectName():
settings.beginGroup(children.objectName())
items = settings.value("items")
selecteditems = settings.value("selecteditems")
selectionMode = settings.value("selectionMode", type=QtWidgets.QAbstractItemView.SelectionMode)
children.setSelectionMode(selectionMode)
# In the first reading the initial values must be established
if items is None:
if children.objectName() == "listwidget_1":
for i in range(10):
children.addItem(QtWidgets.QListWidgetItem(str(i)))
elif children.objectName() == "listwidget_2":
for i in "abcdefghijklmnopqrstuvwxyz":
children.addItem(QtWidgets.QListWidgetItem(i))
else:
stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
while not stream.atEnd():
it = QtWidgets.QListWidgetItem()
stream >> it
children.addItem(it)
stream = QtCore.QDataStream(selecteditems, QtCore.QIODevice.ReadOnly)
while not stream.atEnd():
row = stream.readInt()
it = children.item(row)
it.setSelected(True)
settings.endGroup()
def write_settings(self):
settings = QtCore.QSettings("data.ini", QtCore.QSettings.IniFormat)
childrens = self.findChildren(QtWidgets.QWidget)
for children in childrens:
if isinstance(children, QtWidgets.QListWidget) and children.objectName():
settings.beginGroup(children.objectName())
items = QtCore.QByteArray()
stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
for i in range(children.count()):
stream << children.item(i)
selecteditems = QtCore.QByteArray()
stream = QtCore.QDataStream(selecteditems, QtCore.QIODevice.WriteOnly)
for it in children.selectedItems():
stream.writeInt(children.row(it))
settings.setValue("items", items)
settings.setValue("selecteditems", selecteditems)
settings.setValue("selectionMode", children.selectionMode())
settings.endGroup()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Plus:
import contextlib
from PyQt5 import QtCore, QtGui, QtWidgets
class SettingsManager:
def __init__(self, filename):
self.m_settings = QtCore.QSettings(filename, QtCore.QSettings.IniFormat)
#property
def settings(self):
return self.m_settings
def read(self, widget):
self.settings.beginGroup(widget.objectName())
if isinstance(widget, QtWidgets.QAbstractItemView):
selectionMode = self.settings.value(
"selectionMode", type=QtWidgets.QAbstractItemView.SelectionMode
)
widget.setSelectionMode(selectionMode)
if isinstance(widget, QtWidgets.QListWidget):
items = self.settings.value("items")
selecteditems = self.settings.value("selecteditems")
# In the first reading the initial values must be established
if items is None:
self.read_defaults(widget)
else:
stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
while not stream.atEnd():
it = QtWidgets.QListWidgetItem()
stream >> it
widget.addItem(it)
stream = QtCore.QDataStream(
selecteditems, QtCore.QIODevice.ReadOnly
)
while not stream.atEnd():
row = stream.readInt()
it = widget.item(row)
if it is not None:
it.setSelected(True)
if isinstance(widget, QtWidgets.QTableWidget):
rowCount = self.settings.value("rowCount", type=int)
columnCount = self.settings.value("columnCount", type=int)
widget.setRowCount(rowCount)
widget.setColumnCount(columnCount)
items = self.settings.value("items")
if items is None:
self.read_defaults(widget)
else:
stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
while not stream.atEnd():
it = QtWidgets.QTableWidgetItem()
i = stream.readInt()
j = stream.readInt()
stream >> it
widget.setItem(i, j, it)
selecteditems = self.settings.value("selecteditems")
stream = QtCore.QDataStream(
selecteditems, QtCore.QIODevice.ReadOnly
)
while not stream.atEnd():
i = stream.readInt()
j = stream.readInt()
it = widget.item(i, j)
if it is not None:
it.setSelected(True)
self.settings.endGroup()
def write(self, widget):
self.settings.beginGroup(widget.objectName())
if isinstance(widget, QtWidgets.QAbstractItemView):
self.settings.setValue("selectionMode", widget.selectionMode())
if isinstance(widget, QtWidgets.QListWidget):
items = QtCore.QByteArray()
stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
for i in range(widget.count()):
stream << widget.item(i)
self.settings.setValue("items", items)
selecteditems = QtCore.QByteArray()
stream = QtCore.QDataStream(
selecteditems, QtCore.QIODevice.WriteOnly
)
for it in widget.selectedItems():
stream.writeInt(widget.row(it))
self.settings.setValue("selecteditems", selecteditems)
if isinstance(widget, QtWidgets.QTableWidget):
self.settings.setValue("rowCount", widget.rowCount())
self.settings.setValue("columnCount", widget.columnCount())
items = QtCore.QByteArray()
stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
for i in range(widget.rowCount()):
for j in range(widget.columnCount()):
it = widget.item(i, j)
if it is not None:
stream.writeInt(i)
stream.writeInt(j)
stream << it
self.settings.setValue("items", items)
selecteditems = QtCore.QByteArray()
stream = QtCore.QDataStream(
selecteditems, QtCore.QIODevice.WriteOnly
)
for it in widget.selectedItems():
# print(it.row(), it.column())
stream.writeInt(it.row())
stream.writeInt(it.column())
self.settings.setValue("selecteditems", selecteditems)
self.settings.endGroup()
def release(self):
self.m_settings.sync()
def read_defaults(self, widget):
if widget.objectName() == "listwidget_1":
widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
for i in range(10):
widget.addItem(QtWidgets.QListWidgetItem(str(i)))
elif widget.objectName() == "listwidget_2":
widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
for i in "abcdefghijklmnopqrstuvwxyz":
widget.addItem(QtWidgets.QListWidgetItem(i))
elif widget.objectName() == "tablewidget":
widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
widget.setRowCount(10)
widget.setColumnCount(10)
for i in range(widget.rowCount()):
for j in range(widget.columnCount()):
it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
widget.setItem(i, j, it)
#contextlib.contextmanager
def settingsContext(filename):
manager = SettingsManager(filename)
try:
yield manager
finally:
manager.release()
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.listwidget_1 = QtWidgets.QListWidget(objectName="listwidget_1")
listwidget_2 = QtWidgets.QListWidget(objectName="listwidget_2")
tablewidget = QtWidgets.QTableWidget(objectName="tablewidget")
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.listwidget_1)
lay.addWidget(listwidget_2)
lay.addWidget(tablewidget)
self.read_settings()
def closeEvent(self, event):
self.write_settings()
super().closeEvent(event)
def read_settings(self):
with settingsContext("data.ini") as m:
for children in self.findChildren(QtWidgets.QWidget):
if children.objectName():
m.read(children)
def write_settings(self):
with settingsContext("data.ini") as m:
for children in self.findChildren(QtWidgets.QWidget):
if children.objectName():
m.write(children)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())

How to format the list items of QCompleter's popup list properly?

I want to investigate how to make a small user interface in which a user can type some letters and gets some suggestions based on a given data source (list here) which makes searches easier. For this purpose i am using Qt's QCompleter class.
In the matching elements the typed letters shall be highlighted with HTML like the example in the code below: Au<b>st</b>ria.
Finally i merged some SO answers (see How to make item view render rich (html) text in Qt) and tutorials to a small standalone module:
from PySide import QtCore, QtGui
class HTMLDelegate(QtGui.QStyledItemDelegate):
""" From: https://stackoverflow.com/a/5443112/1504082 """
def paint(self, painter, option, index):
options = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(options, index)
if options.widget is None:
style = QtGui.QApplication.style()
else:
style = options.widget.style()
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
doc.setTextWidth(option.rect.width())
options.text = ""
style.drawControl(QtGui.QStyle.CE_ItemViewItem, options, painter)
ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
# Highlighting text if item is selected
# if options.state & QtGui.QStyle.State_Selected:
# ctx.palette.setColor(QtGui.QPalette.Text,
# options.palette.color(QtGui.QPalette.Active,
# QtGui.QPalette.HighlightedText))
textRect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText,
options)
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
doc.documentLayout().draw(painter, ctx)
painter.restore()
def sizeHint(self, option, index):
options = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(options, index)
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
doc.setTextWidth(options.rect.width())
return QtCore.QSize(doc.size().width(), doc.size().height())
class CustomQCompleter(QtGui.QCompleter):
""" Implement "contains" filter mode as the filter mode "contains" is not
available in Qt < 5.2
From: https://stackoverflow.com/a/7767999/1504082 """
def __init__(self, parent=None):
super(CustomQCompleter, self).__init__(parent)
self.local_completion_prefix = ""
self.source_model = None
self.delegate = HTMLDelegate()
def setModel(self, model):
self.source_model = model
super(CustomQCompleter, self).setModel(self.source_model)
def updateModel(self):
local_completion_prefix = self.local_completion_prefix
# see: http://doc.qt.io/qt-4.8/model-view-programming.html#proxy-models
class InnerProxyModel(QtGui.QSortFilterProxyModel):
def filterAcceptsRow(self, sourceRow, sourceParent):
# model index mapping by row, 1d model => column is always 0
index = self.sourceModel().index(sourceRow, 0, sourceParent)
source_data = self.sourceModel().data(index, QtCore.Qt.DisplayRole)
# performs case insensitive matching
# return True if item shall stay in th returned filtered data
# return False to reject an item
return local_completion_prefix.lower() in source_data.lower()
proxy_model = InnerProxyModel()
proxy_model.setSourceModel(self.source_model)
super(CustomQCompleter, self).setModel(proxy_model)
# #todo: Why to be set here again?
self.popup().setItemDelegate(self.delegate)
def splitPath(self, path):
self.local_completion_prefix = path
self.updateModel()
return ""
class AutoCompleteEdit(QtGui.QLineEdit):
""" Basically from:
http://doc.qt.io/qt-5/qtwidgets-tools-customcompleter-example.html
"""
def __init__(self, list_data, separator=' ', addSpaceAfterCompleting=True):
super(AutoCompleteEdit, self).__init__()
# settings
self._separator = separator
self._addSpaceAfterCompleting = addSpaceAfterCompleting
# completer
self._completer = CustomQCompleter(self)
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self._completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.model = QtGui.QStringListModel(list_data)
self._completer.setModel(self.model)
# connect the completer to the line edit
self._completer.setWidget(self)
# trigger insertion of the selected completion when its activated
self.connect(self._completer,
QtCore.SIGNAL('activated(QString)'),
self._insertCompletion)
self._ignored_keys = [QtCore.Qt.Key_Enter,
QtCore.Qt.Key_Return,
QtCore.Qt.Key_Escape,
QtCore.Qt.Key_Tab]
def _insertCompletion(self, completion):
"""
This is the event handler for the QCompleter.activated(QString) signal,
it is called when the user selects an item in the completer popup.
It will remove the already typed string with the one of the completion.
"""
stripped_text = self.text()[:-len(self._completer.completionPrefix())]
extra_text = completion # [-extra:]
if self._addSpaceAfterCompleting:
extra_text += ' '
self.setText(stripped_text + extra_text)
def textUnderCursor(self):
text = self.text()
textUnderCursor = ''
i = self.cursorPosition() - 1
while i >= 0 and text[i] != self._separator:
textUnderCursor = text[i] + textUnderCursor
i -= 1
return textUnderCursor
def keyPressEvent(self, event):
if self._completer.popup().isVisible():
if event.key() in self._ignored_keys:
event.ignore()
return
super(AutoCompleteEdit, self).keyPressEvent(event)
completionPrefix = self.textUnderCursor()
if completionPrefix != self._completer.completionPrefix():
self._updateCompleterPopupItems(completionPrefix)
if len(event.text()) > 0 and len(completionPrefix) > 0:
self._completer.complete()
if len(completionPrefix) == 0:
self._completer.popup().hide()
def _updateCompleterPopupItems(self, completionPrefix):
"""
Filters the completer's popup items to only show items
with the given prefix.
"""
self._completer.setCompletionPrefix(completionPrefix)
# self._completer.popup().setCurrentIndex(
# self._completer.completionModel().index(0, 0))
if __name__ == '__main__':
def demo():
import sys
app = QtGui.QApplication(sys.argv)
values = ['Germany',
'Au<b>st</b>ria',
'Switzerland',
'Hungary',
'The United Kingdom of Great Britain and Northern Ireland']
editor = AutoCompleteEdit(values)
window = QtGui.QWidget()
hbox = QtGui.QHBoxLayout()
hbox.addWidget(editor)
window.setLayout(hbox)
window.show()
sys.exit(app.exec_())
demo()
My problem is the suggestion of user Timo in the answer https://stackoverflow.com/a/5443112/1504082:
After line: 'doc.setHtml(options.text)', you need to set also doc.setTextWidth(option.rect.width()), otherwise the delegate wont render longer content correctly in respect to target drawing area. For example does not wrap words in QListView.
So i did this to avoid cropping of long text in the completer's popup. But i get the following output:
Where does this additional vertical margin come from?
I investigated this a bit and i see that the sizeHint method of HTMLDelegate is sometimes called with an options parameter which contains a rectangle with attributes (0, 0, 0, 0). And the display behaviour finally changes after the call of doc.setTextWidth(options.rect.width()). But i couldnt finally find out who calls it with this parameter and how i could properly fix this.
Can somebody explain where this comes from and how i can fix this porperly?
Finally i found another way to realize it using the idea of https://stackoverflow.com/a/8036666/1504082. Its much more forward for me without all this custom drawing things which i dont understand yet :)
from PySide import QtCore, QtGui
class TaskDelegate(QtGui.QItemDelegate):
# based on https://stackoverflow.com/a/8036666/1504082
# https://doc.qt.io/archives/qt-4.7/qitemdelegate.html#drawDisplay
# https://doc.qt.io/archives/qt-4.7/qwidget.html#render
margin_x = 5
margin_y = 3
def drawDisplay(self, painter, option, rect, text):
label = self.make_label(option, text)
# calculate render anchor point
point = rect.topLeft()
point.setX(point.x() + self.margin_x)
point.setY(point.y() + self.margin_y)
label.render(painter, point, renderFlags=QtGui.QWidget.DrawChildren)
def sizeHint(self, option, index):
# get text using model and index
text = index.model().data(index)
label = self.make_label(option, text)
return QtCore.QSize(label.width(), label.height() + self.margin_y)
def make_label(self, option, text):
label = QtGui.QLabel(text)
if option.state & QtGui.QStyle.State_Selected:
p = option.palette
p.setColor(QtGui.QPalette.WindowText,
p.color(QtGui.QPalette.Active,
QtGui.QPalette.HighlightedText)
)
label.setPalette(p)
label.setStyleSheet("border: 1px dotted black")
# adjust width according to widget's target width
label.setMinimumWidth(self.target_width - (2 * self.margin_x))
label.setMaximumWidth(self.target_width - self.margin_x)
label.setWordWrap(True)
label.adjustSize()
return label
class CustomQCompleter(QtGui.QCompleter):
""" Implement "contains" filter mode as the filter mode "contains" is not
available in Qt < 5.2
From: https://stackoverflow.com/a/7767999/1504082 """
def __init__(self, parent=None):
super(CustomQCompleter, self).__init__(parent)
self.local_completion_prefix = ""
self.source_model = None
self.delegate = TaskDelegate()
# widget not set yet
# self.delegate.target_width = self.widget().width()
def setModel(self, model):
self.source_model = model
super(CustomQCompleter, self).setModel(self.source_model)
def updateModel(self):
local_completion_prefix = self.local_completion_prefix
# see: http://doc.qt.io/qt-4.8/model-view-programming.html#proxy-models
class InnerProxyModel(QtGui.QSortFilterProxyModel):
def filterAcceptsRow(self, sourceRow, sourceParent):
# model index mapping by row, 1d model => column is always 0
index = self.sourceModel().index(sourceRow, 0, sourceParent)
source_data = self.sourceModel().data(index, QtCore.Qt.DisplayRole)
# performs case insensitive matching
# return True if item shall stay in th returned filtered data
# return False to reject an item
return local_completion_prefix.lower() in source_data.lower()
proxy_model = InnerProxyModel()
proxy_model.setSourceModel(self.source_model)
super(CustomQCompleter, self).setModel(proxy_model)
# #todo: Why to be set here again?
# -> rescale popup list items to widget width
self.delegate.target_width = self.widget().width()
self.popup().setItemDelegate(self.delegate)
def splitPath(self, path):
self.local_completion_prefix = path
self.updateModel()
return ""
class AutoCompleteEdit(QtGui.QLineEdit):
""" Basically from:
http://doc.qt.io/qt-5/qtwidgets-tools-customcompleter-example.html
"""
def __init__(self, list_data, separator=' ', addSpaceAfterCompleting=True):
super(AutoCompleteEdit, self).__init__()
# settings
self._separator = separator
self._addSpaceAfterCompleting = addSpaceAfterCompleting
# completer
self._completer = CustomQCompleter(self)
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self._completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.model = QtGui.QStringListModel(list_data)
self._completer.setModel(self.model)
# connect the completer to the line edit
self._completer.setWidget(self)
# trigger insertion of the selected completion when its activated
self.connect(self._completer,
QtCore.SIGNAL('activated(QString)'),
self._insertCompletion)
self._ignored_keys = [QtCore.Qt.Key_Enter,
QtCore.Qt.Key_Return,
QtCore.Qt.Key_Escape,
QtCore.Qt.Key_Tab]
def _insertCompletion(self, completion):
"""
This is the event handler for the QCompleter.activated(QString) signal,
it is called when the user selects an item in the completer popup.
It will remove the already typed string with the one of the completion.
"""
stripped_text = self.text()[:-len(self._completer.completionPrefix())]
extra_text = completion # [-extra:]
if self._addSpaceAfterCompleting:
extra_text += ' '
self.setText(stripped_text + extra_text)
def textUnderCursor(self):
text = self.text()
textUnderCursor = ''
i = self.cursorPosition() - 1
while i >= 0 and text[i] != self._separator:
textUnderCursor = text[i] + textUnderCursor
i -= 1
return textUnderCursor
def keyPressEvent(self, event):
if self._completer.popup().isVisible():
if event.key() in self._ignored_keys:
event.ignore()
return
super(AutoCompleteEdit, self).keyPressEvent(event)
completionPrefix = self.textUnderCursor()
if completionPrefix != self._completer.completionPrefix():
self._updateCompleterPopupItems(completionPrefix)
if len(event.text()) > 0 and len(completionPrefix) > 0:
self._completer.complete()
if len(completionPrefix) == 0:
self._completer.popup().hide()
def _updateCompleterPopupItems(self, completionPrefix):
"""
Filters the completer's popup items to only show items
with the given prefix.
"""
self._completer.setCompletionPrefix(completionPrefix)
# self._completer.popup().setCurrentIndex(
# self._completer.completionModel().index(0, 0))
if __name__ == '__main__':
def demo():
import sys
app = QtGui.QApplication(sys.argv)
values = ['Germany',
'Au<b>st</b>ria',
'Switzerland',
'Hungary',
'The United Kingdom of Great Britain and Northern Ireland',
'USA']
editor = AutoCompleteEdit(values)
window = QtGui.QWidget()
hbox = QtGui.QHBoxLayout()
hbox.addWidget(editor)
window.setLayout(hbox)
window.show()
sys.exit(app.exec_())
demo()

Drag and Dropping Rows between two separate QTableWidgets

Background:
I have two separate QTableWidgets on my Main Window. Both of which are dynamically added in python. I have implemented pyqt code, which can be found under three_pineapples solution here.
My Problem
I want to be able to drag and drop table rows from one table, to another. For example:
If I attempt to drag Item B from the Left Table into the Right Table
This would be the outcome
Any suggestions on how to get this desired behavior?
I took a look at the #three_pineapples' code, didn't understand a half and deleted that half. Works with multiple row selection.
import sys
from PyQt4.QtGui import *
class TableWidgetDragRows(QTableWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setDragDropOverwriteMode(False)
# self.setSelectionMode(QAbstractItemView.SingleSelection)
self.last_drop_row = None
# Override this method to get the correct row index for insertion
def dropMimeData(self, row, col, mimeData, action):
self.last_drop_row = row
return True
def dropEvent(self, event):
# The QTableWidget from which selected rows will be moved
sender = event.source()
# Default dropEvent method fires dropMimeData with appropriate parameters (we're interested in the row index).
super().dropEvent(event)
# Now we know where to insert selected row(s)
dropRow = self.last_drop_row
selectedRows = sender.getselectedRowsFast()
# Allocate space for transfer
for _ in selectedRows:
self.insertRow(dropRow)
# if sender == receiver (self), after creating new empty rows selected rows might change their locations
sel_rows_offsets = [0 if self != sender or srow < dropRow else len(selectedRows) for srow in selectedRows]
selectedRows = [row + offset for row, offset in zip(selectedRows, sel_rows_offsets)]
# copy content of selected rows into empty ones
for i, srow in enumerate(selectedRows):
for j in range(self.columnCount()):
item = sender.item(srow, j)
if item:
source = QTableWidgetItem(item)
self.setItem(dropRow + i, j, source)
# delete selected rows
for srow in reversed(selectedRows):
sender.removeRow(srow)
event.accept()
def getselectedRowsFast(self):
selectedRows = []
for item in self.selectedItems():
if item.row() not in selectedRows:
selectedRows.append(item.row())
selectedRows.sort()
return selectedRows
class Window(QWidget):
def __init__(self):
super().__init__()
layout = QHBoxLayout()
self.setLayout(layout)
self.table_widgets = []
for _ in range(3):
tw = TableWidgetDragRows()
tw.setColumnCount(2)
tw.setHorizontalHeaderLabels(['Colour', 'Model'])
self.table_widgets.append(tw)
layout.addWidget(tw)
filled_widget = self.table_widgets[0]
items = [('Red', 'Toyota'), ('Blue', 'RV'), ('Green', 'Beetle')]
for i, (colour, model) in enumerate(items):
c = QTableWidgetItem(colour)
m = QTableWidgetItem(model)
filled_widget.insertRow(filled_widget.rowCount())
filled_widget.setItem(i, 0, c)
filled_widget.setItem(i, 1, m)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

add different length columns to gtk TreeStore(Treeview)

I want to display two levels of hierarchical data using gtk Treeview(with model gtk Treestore)
The data is in the following format:
**First(parent)** level
col_a, col_b, col_c, col_d, col_e
val_a, val_b, val_c, val_d, val_e
**Second(child)** level
col_x, col_y, col_z
val_x, val_y, val_z
And the hierarchy of data is as follows:
> val_a1, val_b1, val_c1, val_d1, val_e1
val_x1, val_y1, val_z1
val_x2, val_y2, val_z2
> val_a2, val_b2, val_c2, val_s2, val_e2
val_x3, val_y3, val_z3
> val_a3, val_b3, val_c3, val_d3, val_e3
> val_a4, val_b4, val_c4, val_d4, val_e4
val_x4, val_y4, val_z4
val_x5, val_y5, val_z5
The following pygtk code is what I have tried(Modified the code from gtk tutorial)
import pygtk
pygtk.require('2.0')
import gtk
data = [
[('val_a1', 'val_b1', 'val_c1', 'val_d1', 'val_e1'), ('val_x1', 'val_y1', 'val_z1'), ('val_x2', 'val_y2', 'val_z2')],
[('val_a2', 'val_b2', 'val_c2', 'val_d2', 'val_e2'), ('val_x3', 'val_y3', 'val_z3')],
[('val_a3', 'val_b3', 'val_c3', 'val_d3', 'val_e3')],
[('val_a4', 'val_b4', 'val_c4', 'val_d4', 'val_e4'), ('val_x4', 'val_y4', 'val_z4'), ('val_x5', 'val_y5', 'val_z5')],
]
class BasicTreeViewExample:
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_title("Basic TreeView Example")
self.window.set_size_request(200, 200)
self.window.connect("delete_event", self.delete_event)
self.treestore = gtk.TreeStore(str, str, str, str, str)
for detail in data:
for index, elem in enumerate(detail):
if index == 0:
piter = self.treestore.append(None, elem)
else:
self.treestore.append(piter, elem)
self.treeview = gtk.TreeView(self.treestore)
for i in range(5):
tvcolumn = gtk.TreeViewColumn('Column %s' % (i))
self.treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', i)
self.window.add(self.treeview)
self.window.show_all()
def main():
gtk.main()
if __name__ == "__main__":
tvexample = BasicTreeViewExample()
main()
But, I'm getting the following error when I try running the above code:
Traceback (most recent call last):
File "test.py", line 55, in <module>
tvexample = BasicTreeViewExample()
File "test.py", line 33, in __init__
self.treestore.append(piter, detail[index])
ValueError: row sequence has wrong length
So my questions are:
How can I add data to gtk TreeStore with different number of columns in the different levels of hierarchy
Also, Is it possible to display column names for each row in the gtk treestore
i.e In the Treeview I want to see the output as follows:
col_a, col_b, col_c, col_d, col_e
> val_a1, val_b1, val_c1, val_d1, val_e1
col_x, col_y, col_z
val_x1, val_y1, val_z1
col_x, col_y, col_z
val_x2, val_y2, val_z2
col_a, col_b, col_c, col_d, col_e
> val_a2, val_b2, val_c2, val_s2, val_e2
col_x, col_y, col_z
val_x3, val_y3, val_z3
col_a, col_b, col_c, col_d, col_e
> val_a3, val_b3, val_c3, val_d3, val_e3
col_a, col_b, col_c, col_d, col_e
> val_a4, val_b4, val_c4, val_d4, val_e4
col_x, col_y, col_z
val_x4, val_y4, val_z4
col_x, col_y, col_z
val_x5, val_y5, val_z5
If this is not possible using the treeview, is there any alternative/workarounds using which I can achieve the above?
Short answers and introduction
How can I add data to gtk.TreeStore with different number of columns in the different levels of hierarchy?
Simple: you can't. GtkListStore as well as GtkTreeStore are designed to hold
data as a table. Columns are defined in a fixed way with an index and a data
type. The only difference between a ListStore and a TreeStore is that in a
TreeStore, rows have a hierarchy. Even worse, the GtkTreeView widget also
expects data to be stored as a table, as each row will unconditionally fetch
the cells using their column index, and expects to find something there.
Unless you write your own widget, but you probably don't want to
(God, this file is 16570 lines long...).
However, if you can't write your own widget, you still could write your own
model. And this will give you some flexibility.
Also, is it possible to display column names for each row in the gtk.TreeStore ?
Displaying data in the TreeView involve two components: the GtkTreeView itself,
that fetches data in the TreeStore and display them. The TreeView widget doesn't
have the feature of displaying headers for each row. But there are some tricks
to process data between the model and the view, which could end to the desired
effect, though not that nice probably.
Basics
So, the TreeView expects to work on a table of data, and we can't change that.
OK. But we still can trick it into thinking the data is a table, when actually
it isn't... Let's start with the view. We need at least five columns to display
the data of the parents. The children can then use only three columns out of
these five, so this is fine.
Note that columns of the model do not always map to a column in the tree view.
They actually map to some properties of cell renderers. For example, you can
have a column in the model that defines the background color of the row,
or a column that defines an icon to display. Columns in the view are just a way
to align groups of cell renderers, possibly under a header. But here, let's
assume all values are text that should go into a single CellRendererText in its
own column.
Parents will use all five columns while children will use only the columns 2, 3
and 4. We'll then trick the model to return an empty text when data isn't
available for the target cell.
Creating a new TreeModel
Some explainations about implementing a custom GtkTreeModel in PyGTK are
available in this tutorial.
This is a sample implementation of it:
import pygtk
pygtk.require('2.0')
import gtk
data = [
[('val_a1', 'val_b1', 'val_c1', 'val_d1', 'val_e1'), ('val_x1', 'val_y1', 'val_z1'), ('val_x2', 'val_y2', 'val_z2')],
[('val_a2', 'val_b2', 'val_c2', 'val_d2', 'val_e2'), ('val_x3', 'val_y3', 'val_z3')],
[('val_a3', 'val_b3', 'val_c3', 'val_d3', 'val_e3')],
[('val_a4', 'val_b4', 'val_c4', 'val_d4', 'val_e4'), ('val_x4', 'val_y4', 'val_z4'), ('val_x5', 'val_y5', 'val_z5')],
]
class MyTreeModel(gtk.GenericTreeModel):
# The columns exposed by the model to the view
column_types = (str, str, str, str, str)
def __init__(self, data):
gtk.GenericTreeModel.__init__(self)
self.data = data
def on_get_flags(self):
"""
Get Model capabilities
"""
return gtk.TREE_MODEL_ITERS_PERSIST
def on_get_n_columns(self):
"""
Get number of columns in the model
"""
return len(self.column_types)
def on_get_column_type(self, n):
"""
Get data type of a specified column in the model
"""
return self.column_types[n]
def on_get_iter(self, path):
"""
Obtain a reference to the row at path. For us, this is a tuple that
contain the position of the row in the double list of data.
"""
if len(path) > 2:
return None # Invalid path
parent_idx = path[0]
if parent_idx >= len(self.data):
return None # Invalid path
first_level_list = self.data[parent_idx]
if len(path) == 1:
# Access the parent at index 0 in the first level list
return (parent_idx, 0)
else:
# Access a child, at index path[1] + 1 (0 is the parent)
child_idx = path[1] + 1
if child_idx >= len(first_level_list):
return None # Invalid path
else:
return (parent_idx, child_idx)
def on_get_path(self, iter_):
"""
Get a path from a rowref (this is the inverse of on_get_iter)
"""
parent_idx, child_idx = iter_
if child_idx == 0:
return (parent_idx, )
else:
(parent_idx, child_idx-1)
def on_get_value(self, iter_, column):
"""
This is where the view asks for values. This is thus where we
start mapping our data model to a fake table to present to the view
"""
parent_idx, child_idx = iter_
item = self.data[parent_idx][child_idx]
# For parents, map columns 1:1 to data
if child_idx == 0:
return item[column]
# For children, we have to fake some columns
else:
if column == 0 or column == 4:
return "" # Fake empty text
else:
return item[column-1] # map 1, 2, 3 to 0, 1, 2.
def on_iter_next(self, iter_):
"""
Get the next sibling of the item pointed by iter_
"""
parent_idx, child_idx = iter_
# For parents, point to the next parent
if child_idx == 0:
next_parent_idx = parent_idx + 1
if next_parent_idx < len(self.data):
return (next_parent_idx, 0)
else:
return None
# For children, get next tuple in the list
else:
next_child_idx = child_idx + 1
if next_child_idx < len(self.data[parent_idx]):
return (parent_idx, next_child_idx)
else:
return None
def on_iter_has_child(self, iter_):
"""
Tells if the row referenced by iter_ has children
"""
parent_idx, child_idx = iter_
if child_idx == 0 and len(self.data[parent_idx]) > 1:
return True
else:
return False
def on_iter_children(self, iter_):
"""
Return a row reference to the first child row of the row specified
by iter_. If iter_ is None, a reference to the first top level row
is returned. If there is no child row None is returned.
"""
if iter_ is None:
return (0, 0)
parent_idx, child_idx = iter_
if self.on_iter_has_child(iter_):
return (parent_idx, 1)
else:
return None
def on_iter_n_children(self, iter_):
"""
Return the number of child rows that the row specified by iter_
has. If iter_ is None, the number of top level rows is returned.
"""
if iter_ is None:
return len(self.data)
else:
parent_idx, child_idx = iter_
if child_idx == 0:
return len(self.data[parent_idx]) - 1
else:
return 0
def on_iter_nth_child(self, iter_, n):
"""
Return a row reference to the nth child row of the row specified by
iter_. If iter_ is None, a reference to the nth top level row is
returned.
"""
if iter_ is None:
if n < len(self.data):
return (n, 0)
else:
return None
else:
parent_idx, child_idx = iter_
if child_idx == 0:
if n+1 < len(self.data[parent_idx]):
return (parent_idx, n+1)
else:
return None
else:
return None
def on_iter_parent(self, iter_):
"""
Get a reference to the parent
"""
parent_idx, child_idx = iter_
if child_idx == 0:
return None
else:
return (parent_idx, 0)
class BasicTreeViewExample:
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_title("Basic TreeView Example")
self.window.set_size_request(200, 200)
self.window.connect("delete_event", self.delete_event)
# Create the model with data in it
self.model = MyTreeModel(data)
self.treeview = gtk.TreeView(self.model)
for i in range(5):
tvcolumn = gtk.TreeViewColumn('Column %s' % (i))
self.treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', i)
self.window.add(self.treeview)
self.window.show_all()
def main():
gtk.main()
if __name__ == "__main__":
tvexample = BasicTreeViewExample()
main()
And the result:
Faking headers in cells
Let's now add some kind of title in each cell using the model to generate
the desired data. Full code is here.
class MyTreeModel(gtk.GenericTreeModel):
# The columns exposed by the model to the view
column_types = (str, str, str, str, str)
# Column headers
parent_headers = ("P.Col 1", "P.Col 2", "P.Col 3", "P.Col 4", "P.Col 5")
child_headers = ("C.Col 1", "C.Col 2", "C.Col 3")
...
def on_get_value(self, iter_, column):
"""
This is where the view asks for values. This is thus where we
start mapping our data model to a fake table to present to the view
"""
parent_idx, child_idx = iter_
item = self.data[parent_idx][child_idx]
# For parents, map columns 1:1 to data
if child_idx == 0:
return self.markup(item[column], column, False)
# For children, we have to fake some columns
else:
if column == 0 or column == 4:
return "" # Fake empty text
else:
# map 1, 2, 3 to 0, 1, 2.
return self.markup(item[column-1], column-1, True)
def markup(self, text, column, is_child):
"""
Produce a markup for a cell with a title and a text
"""
headers = self.child_headers if is_child else self.parent_headers
title = headers[column]
return "<b>%s</b>\n%s"%(title, text)
...
class BasicTreeViewExample:
def __init__(self):
...
self.treeview = gtk.TreeView(self.model)
self.treeview.set_headers_visible(False)
for i in range(5):
...
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'markup', i)
...
And the result:
Using set_cell_data_func or TreeModelFilter
Provided that you manage to fit your data into a ListStore or TreeStore, that
is to say you find a trick so that parents and children share the same amount
and type of columns, you can then manipulate data using either a
GtkTreeCellDataFunc
or a GtkTreeModelFilter.
PyGTK documentation provides examplefor Cell Data Functions
and Tree Model Filters.
Adding column headers using these concepts for example maybe easier than
creating a full custom model.
Here is the code using TreeCellDataFunc.
Note how the data input has been formatted so that children and parents have the
same amount of data. This is a condition to be able to use GtkTreeStore.
import pygtk
pygtk.require('2.0')
import gtk
data = [
[('val_a1', 'val_b1', 'val_c1', 'val_d1', 'val_e1'), ('', 'val_x1', 'val_y1', 'val_z1', ''), ('', 'val_x2', 'val_y2', 'val_z2', '')],
[('val_a2', 'val_b2', 'val_c2', 'val_d2', 'val_e2'), ('', 'val_x3', 'val_y3', 'val_z3', '')],
[('val_a3', 'val_b3', 'val_c3', 'val_d3', 'val_e3')],
[('val_a4', 'val_b4', 'val_c4', 'val_d4', 'val_e4'), ('', 'val_x4', 'val_y4', 'val_z4', ''), ('', 'val_x5', 'val_y5', 'val_z5', '')],
]
class BasicTreeViewExample:
parent_headers = ("P.Col 1", "P.Col 2", "P.Col 3", "P.Col 4", "P.Col 5")
child_headers = ("C.Col 1", "C.Col 2", "C.Col 3")
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_title("Basic TreeView Example")
self.window.set_size_request(200, 200)
self.window.connect("delete_event", self.delete_event)
self.treestore = gtk.TreeStore(str, str, str, str, str)
for detail in data:
for index, elem in enumerate(detail):
if index == 0:
piter = self.treestore.append(None, elem)
else:
self.treestore.append(piter, elem)
self.treeview = gtk.TreeView(self.treestore)
for i in range(5):
tvcolumn = gtk.TreeViewColumn('Column %s' % (i))
self.treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
# Delegate data fetching to callback
tvcolumn.set_cell_data_func(cell, self.cell_add_header, i)
self.window.add(self.treeview)
self.window.show_all()
def cell_add_header(self, treeviewcolumn, cell, model, iter_, column):
text = model.get_value(iter_, column)
if model.iter_parent(iter_) is None:
# This is a parent
title = self.parent_headers[column]
markup = "<b>%s</b>\n%s"%(title, text)
else:
# We have a child
if column == 0 or column == 4:
# Cell is not used by child, leave it empty
markup = ""
else:
title = self.child_headers[column-1]
markup = "<b>%s</b>\n%s"%(title, text)
cell.set_property('markup', markup)
def main():
gtk.main()
if __name__ == "__main__":
tvexample = BasicTreeViewExample()
main()
GtkTreeModelFilter leads to pretty much the same thing. The result is the same
than in Faking headers in cells (except that I forgot to set the headers invisible):
I hope this helped you, and the others that will have the same kind of question!

qt pyside - qsql*model, qabstractitemmodel and qtreeview interaction

I want to produce a simple enough application which uses a QTreeView widget to show hierarchical data from a SQLite3 (flat) table, use QDataWidgetMapper to populate some lineedit fields, allow user to edit, which in turn updates the table. Simple & basic (for most!).
I have been working on the basis that the following process would be the best way of doing this:
Connect to Dbase
Query data
Create and populate custom QAbstractItemModel from the data (manipulating it through a dict to create nodes, parents and children dynamically - for each dict entry a 'node' is generated with an associated parent)
Use QDatawidgetmapper to populate other widgets
User edits data
QAbstractItemModel (QAIM) is updated
Then have to run an UPDATE, INSERT or whatever query using new values in the QAIM model.
Refresh the QAIM and associated widgets.
I realise if I were just using a QTableView or QListView I would not need the custom model and could just write straight back into the database. The process I have outlined above seems to mean having to keep two sets of data going - i.e. the SQLite table and the custom QAIM and ensure that they are both kept up to date. This seems a bit cumbersome to me and I'm sure there must be a better way of doing it where the QTreeView is taking its data straight from the SQLite table - with the obvious need for some manipulation to convert the flat data into hierarchical data.
I am wondering, of course, whether I have completely misunderstood the relationship between QAbstractItemModel and the QSQL*Models and I am overcomplicating it through ignorance?
Thanks
What you want is a proxy model that acts as a bridge between QSql*Model and the view. For that, you need to subclass QAbstractProxyModel. You have to have a consistent way of finding parent-child relationships in proxy model and mapping them to the source model, so that might require keeping some tally in the proxy model.
When you are sub-classing QAbstractProxyModel, you need to re-define, at minimum, these methods:
rowCount
columnCount
parent
index
data
mapToSource
mapFromSource
Also, keep in mind that QAbstractProxyModel does not auto-propagate signals through. So, in order to have the view be aware of changes in source model (like insert, delete, update), you need to pass them in the proxy model (while of course, updating your mappings in the proxy model).
It will require some work, but in the end you'll have a more flexible structure. And it will eliminate all the stuff that you need to do for synchronizing database and custom QAbstractItemModel.
Edit
A custom proxy model that groups items from a flat model according to a given column:
import sys
from collections import namedtuple
import random
from PyQt4 import QtCore, QtGui
groupItem = namedtuple("groupItem",["name","children","index"])
rowItem = namedtuple("rowItem",["groupIndex","random"])
class GrouperProxyModel(QtGui.QAbstractProxyModel):
def __init__(self, parent=None):
super(GrouperProxyModel, self).__init__(parent)
self._rootItem = QtCore.QModelIndex()
self._groups = [] # list of groupItems
self._groupMap = {} # map of group names to group indexes
self._groupIndexes = [] # list of groupIndexes for locating group row
self._sourceRows = [] # map of source rows to group index
self._groupColumn = 0 # grouping column.
def setSourceModel(self, source, groupColumn=0):
super(GrouperProxyModel, self).setSourceModel(source)
# connect signals
self.sourceModel().columnsAboutToBeInserted.connect(self.columnsAboutToBeInserted.emit)
self.sourceModel().columnsInserted.connect(self.columnsInserted.emit)
self.sourceModel().columnsAboutToBeRemoved.connect(self.columnsAboutToBeRemoved.emit)
self.sourceModel().columnsRemoved.connect(self.columnsRemoved.emit)
self.sourceModel().rowsInserted.connect(self._rowsInserted)
self.sourceModel().rowsRemoved.connect(self._rowsRemoved)
self.sourceModel().dataChanged.connect(self._dataChanged)
# set grouping
self.groupBy(groupColumn)
def rowCount(self, parent):
if parent == self._rootItem:
# root level
return len(self._groups)
elif parent.internalPointer() == self._rootItem:
# children level
return len(self._groups[parent.row()].children)
else:
return 0
def columnCount(self, parent):
if self.sourceModel():
return self.sourceModel().columnCount(QtCore.QModelIndex())
else:
return 0
def index(self, row, column, parent):
if parent == self._rootItem:
# this is a group
return self.createIndex(row,column,self._rootItem)
elif parent.internalPointer() == self._rootItem:
return self.createIndex(row,column,self._groups[parent.row()].index)
else:
return QtCore.QModelIndex()
def parent(self, index):
parent = index.internalPointer()
if parent == self._rootItem:
return self._rootItem
else:
parentRow = self._getGroupRow(parent)
return self.createIndex(parentRow,0,self._rootItem)
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
parent = index.internalPointer()
if parent == self._rootItem:
return self._groups[index.row()].name
else:
parentRow = self._getGroupRow(parent)
sourceRow = self._sourceRows.index(self._groups[parentRow].children[index.row()])
sourceIndex = self.createIndex(sourceRow, index.column(), 0)
return self.sourceModel().data(sourceIndex, role)
return None
def flags(self, index):
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def headerData(self, section, orientation, role):
return self.sourceModel().headerData(section, orientation, role)
def mapToSource(self, index):
if not index.isValid():
return QtCore.QModelIndex()
parent = index.internalPointer()
if not parent.isValid():
return QtCore.QModelIndex()
elif parent == self._rootItem:
return QtCore.QModelIndex()
else:
rowItem_ = self._groups[parent.row()].children[index.row()]
sourceRow = self._sourceRows.index(rowItem_)
return self.createIndex(sourceRow, index.column(), QtCore.QModelIndex())
def mapFromSource(self, index):
rowItem_ = self._sourceRows[index.row()]
groupRow = self._getGroupRow(rowItem_.groupIndex)
itemRow = self._groups[groupRow].children.index(rowItem_)
return self.createIndex(itemRow,index.column(),self._groupIndexes[groupRow])
def _clearGroups(self):
self._groupMap = {}
self._groups = []
self._sourceRows = []
def groupBy(self,column=0):
self.beginResetModel()
self._clearGroups()
self._groupColumn = column
sourceModel = self.sourceModel()
for row in range(sourceModel.rowCount(QtCore.QModelIndex())):
groupName = sourceModel.data(self.createIndex(row,column,0),
QtCore.Qt.DisplayRole)
groupIndex = self._getGroupIndex(groupName)
rowItem_ = rowItem(groupIndex,random.random())
self._groups[groupIndex.row()].children.append(rowItem_)
self._sourceRows.append(rowItem_)
self.endResetModel()
def _getGroupIndex(self, groupName):
""" return the index for a group denoted with name.
if there is no group with given name, create and then return"""
if groupName in self._groupMap:
return self._groupMap[groupName]
else:
groupRow = len(self._groupMap)
groupIndex = self.createIndex(groupRow,0,self._rootItem)
self._groupMap[groupName] = groupIndex
self._groups.append(groupItem(groupName,[],groupIndex))
self._groupIndexes.append(groupIndex)
self.layoutChanged.emit()
return groupIndex
def _getGroupRow(self, groupIndex):
for i,x in enumerate(self._groupIndexes):
if id(groupIndex)==id(x):
return i
return 0
def _rowsInserted(self, parent, start, end):
for row in range(start, end+1):
groupName = self.sourceModel().data(self.createIndex(row,self._groupColumn,0),
QtCore.Qt.DisplayRole)
groupIndex = self._getGroupIndex(groupName)
self._getGroupRow(groupIndex)
groupItem_ = self._groups[self._getGroupRow(groupIndex)]
rowItem_ = rowItem(groupIndex,random.random())
groupItem_.children.append(rowItem_)
self._sourceRows.insert(row, rowItem_)
self.layoutChanged.emit()
def _rowsRemoved(self, parent, start, end):
for row in range(start, end+1):
rowItem_ = self._sourceRows[start]
groupIndex = rowItem_.groupIndex
groupItem_ = self._groups[self._getGroupRow(groupIndex)]
childrenRow = groupItem_.children.index(rowItem_)
groupItem_.children.pop(childrenRow)
self._sourceRows.pop(start)
if not len(groupItem_.children):
# remove the group
groupRow = self._getGroupRow(groupIndex)
groupName = self._groups[groupRow].name
self._groups.pop(groupRow)
self._groupIndexes.pop(groupRow)
del self._groupMap[groupName]
self.layoutChanged.emit()
def _dataChanged(self, topLeft, bottomRight):
topRow = topLeft.row()
bottomRow = bottomRight.row()
sourceModel = self.sourceModel()
# loop through all the changed data
for row in range(topRow,bottomRow+1):
oldGroupIndex = self._sourceRows[row].groupIndex
oldGroupItem = self._groups[self._getGroupRow(oldGroupIndex)]
newGroupName = sourceModel.data(self.createIndex(row,self._groupColumn,0),QtCore.Qt.DisplayRole)
if newGroupName != oldGroupItem.name:
# move to new group...
newGroupIndex = self._getGroupIndex(newGroupName)
newGroupItem = self._groups[self._getGroupRow(newGroupIndex)]
rowItem_ = self._sourceRows[row]
newGroupItem.children.append(rowItem_)
# delete from old group
oldGroupItem.children.remove(rowItem_)
if not len(oldGroupItem.children):
# remove the group
groupRow = self._getGroupRow(oldGroupItem.index)
groupName = oldGroupItem.name
self._groups.pop(groupRow)
self._groupIndexes.pop(groupRow)
del self._groupMap[groupName]
self.layoutChanged.emit()

Categories

Resources