Convert node tree to dictionary - python

Below is the node class definition with tree structure (built using node instance) of programming languages. Now how to convert hierarchical node data tree structure to python dictionary using node class method ?
See desired output at bottom.
class Node(object):
def __init__(self, name, parent=None):
self._name = name
self._children = []
self._parent = parent
if parent is not None:
parent.addChild(self)
def addChild(self, child):
self._children.append(child)
def name(self):
return self._name
def setName(self, name):
self._name = name
def child(self, row):
return self._children[row]
def childCount(self):
return len(self._children)
def parent(self):
return self._parent
rootNode = nodeData.Node("books")
web_node = nodeData.Node("web", rootNode)
database_node = nodeData.Node("database", rootNode)
front_end_node = nodeData.Node("front-end", web_node)
back_end_node = nodeData.Node("back-end", web_node)
sql_node = nodeData.Node("sql", database_node)
nosql_node = nodeData.Node("nosql", database_node)
html_node = nodeData.Node("html", front_end_node)
css_node = nodeData.Node("css", front_end_node)
js_node = nodeData.Node("js", front_end_node)
php_node = nodeData.Node("php", back_end_node)
python_node = nodeData.Node("python", back_end_node)
mysql_node = nodeData.Node("mysql", sql_node)
postgresql_node = nodeData.Node("postgresql", sql_node)
mongodb_node = nodeData.Node("mongodb", nosql_node)
cassandra_node = nodeData.Node("cassandra", nosql_node)
html_book_one_node = nodeData.Node("the missing manual", html_node)
html_book_two_node = nodeData.Node("core html5 canvas", html_node)
css_book_one_node = nodeData.Node("css pocket reference", css_node)
css_book_two_node = nodeData.Node("css in depth", css_node)
js_book_one_node = nodeData.Node("you don't know js", js_node)
js_book_two_node = nodeData.Node("eloquent javascript", js_node)
php_book_one_node = nodeData.Node("modern php", php_node)
python_book_one_node = nodeData.Node("dive into python", python_node)
python_book_two_node = nodeData.Node("python for everybody", python_node)
python_book_three_node = nodeData.Node("Think Python", python_node)
mongodb_book_one_node = nodeData.Node("mongodb in action", mongodb_node)
mongodb_two_node = nodeData.Node("scaling mongodb", mongodb_node)
Output
From node tree abstraction to python dictionary
{"books":{
"web":{
"front-end":{
"html":["the missing manual", "core html5 canvas"],
"css":["css pocket reference", "css in depth"],
"js":["you don't know js", "eloquent javascript"]
},
"back-end":{
"php":["modern php"],
"python":["dive into python", "python for everybody",
"Think Python"]
}
},
"database":{
"sql":{
"mysql":[],
"postgresql":[]
},
"nosql":{
"mongodb":["mongodb in action", "scaling mongodb"],
"cassandra":[]
}}}}
Updated Code
class Node(object):
def __init__(self, name, parent=None):
self._name = name
self._children = []
self._parent = parent
if parent is not None:
parent.addChild(self)
def addChild(self, child):
self._children.append(child)
def name(self):
return self._name
def setName(self, name):
self._name = name
def child(self, row):
return self._children[row]
def childCount(self):
return len(self._children)
def parent(self):
return self._parent
class categoryNode(Node):
def __init__(self, name, parent=None):
super(categoryNode, self).__init__(name, parent)
class subCategoryNode(Node):
def __init__(self, name, parent=None):
super(subCategoryNode, self).__init__(name, parent)
class languageNode(Node):
def __init__(self, name, parent=None):
super(languageNode, self).__init__(name, parent)
class BookNode(Node):
def __init__(self, name, parent=None):
super(BookNode, self).__init__(name, parent)
rootNode = Node("books")
web_node = categoryNode("web", rootNode)
database_node = categoryNode("database", rootNode)
front_end_node = subCategoryNode("front-end", web_node)
back_end_node = subCategoryNode("back-end", web_node)
sql_node = subCategoryNode("sql", database_node)
nosql_node = subCategoryNode("nosql", database_node)
html_node = languageNode("html", front_end_node)
css_node = languageNode("css", front_end_node)
js_node = languageNode("js", front_end_node)
php_node = languageNode("php", back_end_node)
python_node = languageNode("python", back_end_node)
mysql_node = languageNode("mysql", sql_node)
postgresql_node = languageNode("postgresql", sql_node)
mongodb_node = languageNode("mongodb", nosql_node)
cassandra_node = languageNode("cassandra", nosql_node)
html_book_one_node = BookNode("the missing manual", html_node)
html_book_two_node = BookNode("core html5 canvas", html_node)
css_book_one_node = BookNode("css pocket reference", css_node)
css_book_two_node = BookNode("css in depth", css_node)
js_book_one_node = BookNode("you don't know js", js_node)
js_book_two_node = BookNode("eloquent javascript", js_node)
php_book_one_node = BookNode("modern php", php_node)
python_book_one_node = BookNode("dive into python", python_node)
python_book_two_node = BookNode("python for everybody", python_node)
python_book_three_node = BookNode("Think Python", python_node)
mongodb_book_one_node = BookNode("mongodb in action", mongodb_node)
mongodb_two_node = BookNode("scaling mongodb", mongodb_node)

You have a bigger problem, because you're using the same class to represent both book categories and actual books. Given this, it is impossible to programmatically determine that mysql_node and postgresql_node are empty categories rather than books.
To make this work how you want, you will need to redesign the data structure. I suggest having a list _children for subcategories and another list _books for book titles (as strings). Note that this data structure is still a little ambiguous because a node with no subcategories and no books could be rendered as an empty list (i.e. a terminal category with no books) or an empty dictionary (i.e. a non-terminal category with no subcategories); I infer from the question that an empty list is the desired result.
class Node:
def __init__(self, name, parent=None):
self._name = name
self._children = []
self._parent = parent
self._books = []
if parent is not None:
parent.addChild(self)
def name(self):
return self._name
def setName(self, name):
self._name = name
def parent(self):
return self._parent
def addChild(self, child):
if self._books:
raise ValueError('Node cannot have both sub-categories and books')
self._children.append(child)
def child(self, row):
return self._children[row]
def childCount(self):
return len(self._children)
def addBook(self, book):
if self._children:
raise ValueError('Node cannot have both sub-categories and books')
self._books.append(book)
def book(self, row):
return self._books[row]
def bookCount(self):
return len(self._books)
rootNode = Node("books")
web_node = Node("web", rootNode)
database_node = Node("database", rootNode)
front_end_node = Node("front-end", web_node)
back_end_node = Node("back-end", web_node)
sql_node = Node("sql", database_node)
nosql_node = Node("nosql", database_node)
html_node = Node("html", front_end_node)
css_node = Node("css", front_end_node)
js_node = Node("js", front_end_node)
php_node = Node("php", back_end_node)
python_node = Node("python", back_end_node)
mysql_node = Node("mysql", sql_node)
postgresql_node = Node("postgresql", sql_node)
mongodb_node = Node("mongodb", nosql_node)
cassandra_node = Node("cassandra", nosql_node)
html_node.addBook("the missing manual")
html_node.addBook("core html5 canvas")
css_node.addBook("css pocket reference")
css_node.addBook("css in depth")
js_node.addBook("you don't know js")
js_node.addBook("eloquent javascript")
php_node.addBook("modern php")
python_node.addBook("dive into python")
python_node.addBook("python for everybody")
python_node.addBook("Think Python")
mongodb_node.addBook("mongodb in action")
mongodb_node.addBook("scaling mongodb")
def node_to_dict(node):
def helper(n):
if n.childCount() > 0:
return { c.name(): helper(c) for c in n._children }
else:
return list(n._books)
return { node.name(): helper(node) }
The result of node_to_dict(rootNode) does == your expected output.

Simple recursive function:
def to_dict(node):
if isinstance(node, nodeData.Node):
return {node._name:to_dict(node._children)}
if all(isinstance(i, nodeData.Node) for i in node):
return (lambda x:x if all(x.values()) else list(x))({i._name:to_dict(i._children) for i in node})
return node
print(to_dict(rootNode))
Output:
{'books': {'web': {'front-end': {'html': ['the missing manual', 'core html5 canvas'], 'css': ['css pocket reference', 'css in depth'], 'js': ["you don't know js", 'eloquent javascript']}, 'back-end': {'php': ['modern php'], 'python': ['dive into python', 'python for everybody', 'Think Python']}}, 'database': {'sql': ['mysql', 'postgresql'], 'nosql': ['mongodb', 'cassandra']}}}

Related

iterating objects in a list through a loop

So I'm just doing a learning project and I need some help.
class Car:
def __init__(self):
self.speed = 0
self.color = ""
self.weight = 0
self.engine = 4
self.name = ""
self.mpg = 25
self.maintenanceLog = []
self.oilChanges = []
#mutator methods
def setSpeed(self, sp):
self.speed = sp
def setColor(self, cl):
self.color = cl
def setWeight(self, w):
self.weight = w
def setEngine(self, e):
self.engine = e
def setName(self, n):
self.name = n
def setMpg(self, mpg):
self.mpg = mpg
def addOilChange(self, oc):
self.oilChanges.append(oc)
def addMaintenance(self, ml):
self.maintenanceLog.append(ml)
#accessor methods
def getSpeed(self):
return self.speed
def getColor(self):
return self.color
def getWeight(self):
return self.weight
def getEngine(self):
return self.engine
def getName(self):
return self.name
def getMPG(self):
return self.mpg
def getAllOilChanges(self):
print("")
print("----------OIL CHANGES----------")
for oc in self.oilChanges:
print(oc)
def getMaintenanceLogs(self):
print("")
print("----------MAINTENANCE LOGS----------")
for ml in self.maintenanceLog:
print(ml)
def setInfo(car):
car.setSpeed(int(input(f"Speed of {car}")))
car.setWeight(int(input(f"Weight of {car}")))
car.setName(input(f"Name of {car}"))
car.setColor(input(f"Color of {car}"))
car.setEngine(int(input(f"Engine of {car}")))
car.setMpg(int(input(f"Miles per Gallon of {car}")))
def getInfo(car):
print(f"Speed of {car} is {car.getSpeed()} mph.")
print(f"Weight of {car} is {car.getWeight()} pounds.")
print(f"Name of {car} is {car.getName()}.")
print(f"Color of {car} is {car.getColor()}.")
print(f"Engine cylinders of {car} are {car.getEngine()}.")
print(f"Miles per Gallon of {car} is {car.getMPG()}.")
def main():
carList = []
Object1= Car()
carList.append(Object1)
print(carList)
for obj in carList:
setInfo(obj)
getInfo(obj)
main()
Thats's the code, now, whenever I run it, I want to get asked Speed of Object1:
Instead, I get asked Speed of <main.Car object at 0x0000024B093CEFD0>:
How can I see the name of the object instead of that hash value... I want to keep adding objects with the class Car and then pass them through a loop to fill in the information regarding the object, but if the list of objects was [Object 1, Object 2, Object 3... Object N] I want it to refer to that name (Object 1) instead of <main.Car object at 0x0000024B093CEFD0>
You can pass the name to use in the prompts as an argument to setInfo().
def setInfo(car, name=None):
if name is None:
name = car.name
car.setSpeed(int(input(f"Speed of {name}")))
car.setWeight(int(input(f"Weight of {name}")))
car.setName(input(f"Name of {name}"))
car.setColor(input(f"Color of {name}"))
car.setEngine(int(input(f"Engine of {name}")))
car.setMpg(int(input(f"Miles per Gallon of {name}")))
and then use that in the loop.
for i, obj in enumerate(carList, 1):
setInfo(obj, f"Object {i}")
getInfo(obj)

QTreeView QAbstractItemModel parent collapses after deleting item and sometimes crashes

Im trying to build a little list of entries within a QTreeView, and based on the example posted here, I got it to delete any child items via the right click context menu i added. but when i delete it the parent tree i have collapses. And in some cases if i delete a certain item in a certain order this crashes
My understanding is that this is because upon deletion the indices of the items changes, and to prevent that QtCore.QPersistentModelIndex() can be utilized according to this thread: How to delete multiple rows in a QTableView widget?
Although that example uses a QStandardItemModel(), since mine uses a QAbstractItemModel() how can I implement a similar concept, and also prevent this from crashing...?
import sys
from functools import partial
from PyQt4 import QtGui, QtCore
HORIZONTAL_HEADERS = ("Asset Name", "Date Added")
class AssetClass(object):
'''
a trivial custom data object
'''
def __init__(self, **kwargs):
if not kwargs.get('name') or not kwargs.get('type'):
return
self.name = kwargs.get('name')
self.date_added = kwargs.get('date_added')
self.type = kwargs.get('type')
def __repr__(self):
return "%s - %s %s" % (self.type, self.name, self.date_added)
class TreeItem(object):
'''
a python object used to return row/column data, and keep note of
it's parents and/or children
'''
def __init__(self, asset, header, parent_item):
self.asset = asset
self.parent_item = parent_item
self.header = header
self.child_items = []
def appendChild(self, item):
self.child_items.append(item)
def removeChild(self, item):
print 'removeChild: item is %s' % item
print 'removeChild: self.child_items is %s' % self.child_items
self.child_items.remove(item)
def child(self, row):
return self.child_items[row]
def childCount(self):
return len(self.child_items)
def columnCount(self):
return 2
def data(self, column):
if self.asset == None:
if column == 0:
return QtCore.QVariant(self.header)
if column == 1:
return QtCore.QVariant("")
else:
if column == 0:
return QtCore.QVariant(self.asset.name)
if column == 1:
return QtCore.QVariant(self.asset.date_added)
return QtCore.QVariant()
def parent(self):
return self.parent_item
def row(self):
if self.parent_item:
return self.parent_item.child_items.index(self)
return 0
class TreeModel(QtCore.QAbstractItemModel):
'''
a model to display a few names, ordered by sex
'''
def __init__(self, parent=None):
super(TreeModel, self).__init__(parent)
self.assets = []
model_data = (("VEHICLE", "Truck", 'May 27th, 2020'),
("VEHICLE", "Car", 'May 25th, 2020'),
("CHARACTER", "Peter", 'May 27th, 2020'),
("CHARACTER", "Rachel", 'May 29th, 2020'),
("PROP", "Chair", 'May 27th, 2020'),
("PROP", "Axe", 'May 17th, 2020'))
for asset_type, name, date in model_data:
asset = AssetClass(type=asset_type, name=name, date_added=date)
self.assets.append(asset)
self.rootItem = TreeItem(None, "ALL", None)
self.parents = {0: self.rootItem}
self.setupModelData()
def columnCount(self, parent=None):
if parent and parent.isValid():
return parent.internalPointer().columnCount()
else:
return len(HORIZONTAL_HEADERS)
def data(self, index, role):
if not index.isValid():
return QtCore.QVariant()
item = index.internalPointer()
if role == QtCore.Qt.DisplayRole:
return item.data(index.column())
if role == QtCore.Qt.UserRole:
if item:
return item.asset
return QtCore.QVariant()
def headerData(self, column, orientation, role):
if (orientation == QtCore.Qt.Horizontal and
role == QtCore.Qt.DisplayRole):
try:
return QtCore.QVariant(HORIZONTAL_HEADERS[column])
except IndexError:
pass
return QtCore.QVariant()
def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parent_item = self.rootItem
else:
parent_item = parent.internalPointer()
childItem = parent_item.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
if not childItem:
return QtCore.QModelIndex()
parent_item = childItem.parent()
if parent_item == self.rootItem:
return QtCore.QModelIndex()
return self.createIndex(parent_item.row(), 0, parent_item)
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.column() > 0:
return 0
if not parent.isValid():
p_Item = self.rootItem
else:
p_Item = parent.internalPointer()
return p_Item.childCount()
def setupModelData(self):
for asset in self.assets:
asset_type = asset.type
if not self.parents.has_key(asset_type):
new_parent = TreeItem(None, asset_type, self.rootItem)
self.rootItem.appendChild(new_parent)
self.parents[asset_type] = new_parent
print 'self.parents: ', self.parents
parent_item = self.parents[asset_type]
new_item = TreeItem(asset, "", parent_item)
parent_item.appendChild(new_item)
def addSubRow(self, new_asset):
asset_type, name, date = new_asset
asset = AssetClass(type=asset_type, name=name, date_added=date)
parent_item = self.parents[asset_type]
already_exists = False
for child in parent_item.child_items:
if child.asset.name == name and child.asset.type == asset_type:
already_exists = True
if already_exists:
print 'this asset already exists'
return
new_item = TreeItem(asset, "", parent_item)
parent_item.appendChild(new_item)
def removeRow(self, rowIndexes):
child_tree_item = rowIndexes[0].internalPointer()
asset_type = rowIndexes[0].parent().data().toString()
parent_item = self.parents[str(asset_type)]
# hint to keep the tree open after deleting: https://stackoverflow.com/questions/48121393/how-to-delete-multiple-rows-in-a-qtableview-widget
self.beginRemoveRows(QtCore.QModelIndex(), rowIndexes[0].row(), rowIndexes[0].row() + 1)
parent_item.removeChild(child_tree_item)
self.endRemoveRows()
def searchModel(self, asset):
'''
get the modelIndex for a given appointment
'''
def searchNode(node):
'''
a function called recursively, looking at all nodes beneath node
'''
for child in node.child_items:
print child.childCount()
if asset == child.asset:
index = self.createIndex(child.row(), 0, child)
return index
if child.childCount() > 0:
result = searchNode(child)
if result:
return result
retarg = searchNode(self.parents[0])
print retarg
return retarg
def findAssetName(self, name):
app = None
for asset in self.assets:
print asset.name
if asset.name == name:
app = asset
break
if app != None:
index = self.searchModel(app)
return (True, index)
return (False, None)
class TreeView(QtGui.QTreeView):
right_button_clicked = QtCore.pyqtSignal(list, int)
def __init__(self, parent=None):
super(TreeView, self).__init__(parent)
# self.clicked.connect(self.on_treeView_clicked)
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.openMenu)
def selectedRows(self):
rows = []
for index in self.selectedIndexes():
if index.column() == 0:
rows.append(index.row())
print type(rows)
return rows
def openMenu(self, position):
indexes = self.selectedIndexes()
if len(indexes) > 0:
level = 0
index = indexes[0]
while index.parent().isValid():
index = index.parent()
level += 1
menu = QtGui.QMenu()
editMenu = None
if level == 0:
editMenu = QtGui.QAction("Edit person", self)
menu.addAction(editMenu)
elif level == 1:
editMenu = QtGui.QAction("Delete", self)
menu.addAction(editMenu)
elif level == 2:
editMenu = QtGui.QAction("Edit object", self)
menu.addAction(editMenu)
if editMenu:
editMenu.triggered.connect(partial(self._on_right_click, indexes, level))
menu.exec_(self.viewport().mapToGlobal(position))
def _on_right_click(self, indexes, level):
self.right_button_clicked.emit(indexes, level)
def delete_test(self):
print 'addButton clicked'
new_asset = ("CHARACTER", "Smith", 'May 28th, 2020')
asset_type, name, date = new_asset
asset = AssetClass(type=asset_type, name=name, date_added=date)
parent_item = self.tree_view.model().parents[asset_type]
already_exists = False
for child in parent_item.child_items:
if child.asset.name == name and child.asset.type == asset_type:
already_exists = True
if already_exists:
print 'this asset already exists'
return
new_item = TreeItem(asset, "", parent_item)
parent_item.appendChild(new_item)
self.tree_view.model().layoutChanged.emit()
class Dialog(QtGui.QDialog):
add_signal = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setMinimumSize(300, 150)
self.model = TreeModel()
layout = QtGui.QVBoxLayout(self)
self.tree_view = TreeView(self)
self.tree_view.setModel(self.model)
self.tree_view.setAlternatingRowColors(True)
self.tree_view.right_button_clicked.connect(self.deleteButtonClicked)
layout.addWidget(self.tree_view)
label = QtGui.QLabel("Search for the following person")
layout.addWidget(label)
buts = []
frame = QtGui.QFrame(self)
layout2 = QtGui.QHBoxLayout(frame)
for asset in self.model.assets:
but = QtGui.QPushButton(asset.name, frame)
buts.append(but)
layout2.addWidget(but)
QtCore.QObject.connect(but, QtCore.SIGNAL("clicked()"), self.but_clicked)
layout.addWidget(frame)
self.add_button = QtGui.QPushButton("Add \"Character - Smith\"")
layout.addWidget(self.add_button)
QtCore.QObject.connect(self.add_button, QtCore.SIGNAL("clicked()"), self.addButtonClicked)
self.delete_button = QtGui.QPushButton("Delete Selected")
layout.addWidget(self.delete_button)
QtCore.QObject.connect(self.delete_button, QtCore.SIGNAL("clicked()"), self.tree_view.clearSelection)
self.but = QtGui.QPushButton("Clear Selection")
layout.addWidget(self.but)
QtCore.QObject.connect(self.but, QtCore.SIGNAL("clicked()"), self.tree_view.clearSelection)
QtCore.QObject.connect(self.tree_view, QtCore.SIGNAL("clicked (QModelIndex)"), self.row_clicked)
def row_clicked(self, index):
'''
when a row is clicked... show the name
'''
print 'row_clicked index type: %s' % index
print self.tree_view.model().data(index, QtCore.Qt.UserRole)
def but_clicked(self):
'''
when a name button is clicked, I iterate over the model,
find the person with this name, and set the treeviews current item
'''
name = self.sender().text()
print "BUTTON CLICKED:", name
result, index = self.model.findAssetName(name)
if result:
if index:
self.tree_view.setCurrentIndex(index)
return
self.tree_view.clearSelection()
def addButtonClicked(self):
print 'addButton clicked'
new_asset = ("CHARACTER", "Smith", 'May 28th, 2020')
self.tree_view.model().addSubRow(new_asset)
self.tree_view.model().layoutChanged.emit()
#QtCore.pyqtSlot(list, int)
def deleteButtonClicked(self, indexes, level):
print 'deleteButton clicked'
self.tree_view.model().removeRow(indexes)
self.tree_view.model().layoutChanged.emit()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
dialog = Dialog()
dialog.show()
sys.exit(app.exec_())
beginRemoveRows() expects the QModelIndex, which is the parent of the QModelIndex to be removed, as the first parameter. Regarding the example that you indicate in the comments of your code in the table type models, the indexes do not have a parent, so it is passed an invalid QModelIndex.
def removeRow(self, rowIndexes):
child_tree_item = rowIndexes[0].internalPointer()
parent_item = child_tree_item.parent()
self.beginRemoveRows(
rowIndexes[0].parent(), rowIndexes[0].row(), rowIndexes[0].row() + 1
)
parent_item.removeChild(child_tree_item)
self.endRemoveRows()

Implementation of clone in QStandardItem subclass

I am using a QStandardItemModel with a QTreeView to display custom Items. The items come in three different types FILTER_TYPE, MODIFIER_TYPE and GROUP_TYPE.
I would like to be able to reorder items within the model using drag and drop in the view (InternalMove). If I understood it correctly, I have to use setItemPrototype(MyItem()) on my model in order for it to use the custom MyItem and not the general QStandardItem when moving items.
My understanding was that a new instance of the custom MyItem gets created and then all data and flags from the old item are copied over to the new item. However, it seems the model only initialises a new MyItem and never copies the data.
Therefore: How do I reimplement QStandardItem.clone() in the MyItem subclass to copy all data and flags into the new item? Do I have to manually go through all the custom data roles and assign their value to the new item?
The Item class looks like this:
class MyItem(QtGui.QStandardItem):
FILTER_TYPE = QtGui.QStandardItem.UserType + 1
MODIFIER_TYPE = QtGui.QStandardItem.UserType + 2
GROUP_TYPE = QtGui.QStandardItem.UserType + 3
TYPE = QtCore.Qt.UserRole + 0
NAME = QtCore.Qt.UserRole + 1
IS_PROCESSED = QtCore.Qt.UserRole + 5
OUTPUT = QtCore.Qt.UserRole + 6
FN = QtCore.Qt.UserRole + 7
DEFAULT_PARAMS = QtCore.Qt.UserRole + 8
PARAMETER_SET = QtCore.Qt.UserRole + 9
def __init__(self):
super().__init__()
self.name = ""
self.full_name = ""
self.description = ""
self.fn = None
self.default_params = None
self.parameter_set = None
self.is_active = True
self.is_processed = False
self.output = None
self.icon = QtGui.QIcon()
def clone(self):
item = Item()
??? WHAT GOES HERE TO COPY ALL DATA AND FLAGS ???
return item
def __setattr__(self, name, value):
if name == 'name':
self.setData(value, self.NAME)
elif name == 'full_name':
self.setData(value, QtCore.Qt.DisplayRole)
self.setData(value, QtCore.Qt.EditRole)
elif name == 'description':
self.setData(value, QtCore.Qt.ToolTipRole)
...
else:
super().__setattr__(name, value)
def __getattribute__(self, name):
if name == 'name':
return self.data(self.NAME)
elif name == 'full_name':
return self.data(QtCore.Qt.DisplayRole)
elif name == 'description':
return self.data(QtCore.Qt.ToolTipRole)
...
else:
return super().__getattribute__(name)
def initializeItem(self, type_, name, full_name, description="", fn=None, default_params=None):
self.name = name
self.full_name = full_name
self.description = description
self.fn = fn
self.default_params = default_params
self.parameter_set = ParameterSet(params_list=default_params)
self.setData(type_, self.TYPE)
flags = QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled
if type_ == self.FILTER_TYPE:
self.icon = QtGui.QIcon('resources/filter.png')
flags = flags|QtCore.Qt.ItemNeverHasChildren
elif type_ == self.MODIFIER_TYPE:
self.icon = QtGui.QIcon('resources/modifier.png')
flags = flags|QtCore.Qt.ItemIsDropEnabled
elif type_ == self.GROUP_TYPE:
self.icon = QtGui.QIcon('resources/folder.png')
flags = flags|QtCore.Qt.ItemIsDropEnabled|QtCore.Qt.ItemIsEditable
self.setFlags(flags)
def type(self):
return self.data(self.TYPE)
The Model implementation looks like this:
from tree.items import MyItem
class TreeModel(QtGui.QStandardItemModel):
def __init__(self):
super().__init__()
self.setItemPrototype(MyItem())
The logic of "clone" is to create an object with the same information of the item, so in this case you are using the roles to store that information so you must copy all that information in the new item, in this case you can use QDataStream:
def clone(self):
item = MyItem()
ba = QtCore.QByteArray()
ds = QtCore.QDataStream(ba, QtCore.QIODevice.WriteOnly)
ds << self
ds = QtCore.QDataStream(ba)
ds >> item
return item

Kivy Tree View how to save the user's selection?

I have a program with Tree View, I want to use the client selection when he presses on one of the labels. The program is based on client-server but the rest of the code is not relevant. the file_system object is CloudSystem type, the CloudSystem class creates a dictionary of the provided path.
.py file
class CloudSystem:
def __init__(self, cloud_path):
self.root = cloud_path
self.cloud_tree = {}
self.current_dict = self.cloud_tree
self.current_dict[os.path.basename(self.root)] = {}
self.cloud_tree = self.create_cloud( self.root)
def create_cloud(self, root_dir):
dir = {}
root_dir = root_dir.rstrip(os.sep)
start = root_dir.rfind(os.sep) + 1
for path, dirs, files in os.walk(root_dir):
folders = path[start:].split(os.sep)
subdir = dict.fromkeys(files)
parent = reduce(dict.get, folders[:-1], dir)
parent[folders[-1]] = subdir
return dir
def to_string(self):
print(self.cloud_tree)
def get_tree(self):
return self.cloud_tree
def populate_tree_view(tree_view, parent, node):
if node is not None:
if parent is None:
for key in node:
tree_node = tree_view.add_node(TreeViewLabel(text=key,
is_open=False))
if node[key] is not None:
populate_tree_view(tree_view, tree_node, node[key])
else:
for key in node:
tree_node = tree_view.add_node(TreeViewLabel(text=key,
is_open=False), parent)
if node[key] is not None:
populate_tree_view(tree_view, tree_node, node[key])
class CloudView(Screen, FloatLayout):
def __init__(self, **kwargs):
super(CloudView, self).__init__(**kwargs)
self.tv = TreeView(root_options=dict(text='My Cloud'),
hide_root=False,
indent_level=4, )
populate_tree_view(self.tv, None, self.show_cloud())
self.add_widget(self.tv)
def show_cloud(self):
s.send('CLOUD'.encode('utf-8'))
file_system = pickle.loads(s.recv(4096))
return file_system.get_tree()
def on_selection(self):
pass
.kv file
<CloudView>:
name: "cloud"
id: cloud_view

wxpython DataViewCtrl - correctly identify drop target

I would like to use a DataViewCtrl with a PyDataViewModel as tree-like control with drag-and-drop support. I am almost there but I cannot figure out how to distinguish between dropping an item between the lines or on top of the parent item. The two screenshots illustrate the issue. In both cases the item identified as the drop target is the parent item.
This is the code:
import wx
import wx.dataview as dv
print(wx.__version__)
class Container(list):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Container {}'.format(self.name)
class Element(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Element {}'.format(self.name)
#property
def len(self):
return str(len(self.name))
class MyTreeListModel(dv.PyDataViewModel):
def __init__(self, data):
dv.PyDataViewModel.__init__(self)
self.data = data
def GetColumnCount(self):
return 2
def GetColumnType(self, col):
mapper = { 0 : 'string',
1 : 'string'
}
return mapper[col]
def GetChildren(self, parent, children):
if not parent:
for cont in self.data:
children.append(self.ObjectToItem(cont))
return len(self.data)
node = self.ItemToObject(parent)
if isinstance(node, Container):
for ds in node:
children.append(self.ObjectToItem(ds))
return len(node)
return 0
def IsContainer(self, item):
if not item:
return True
node = self.ItemToObject(item)
if isinstance(node, Container):
return True
return False
def GetParent(self, item):
if not item:
return dv.NullDataViewItem
node = self.ItemToObject(item)
if isinstance(node, Container):
return dv.NullDataViewItem
elif isinstance(node, Element):
for g in self.data:
try:
g.index(node)
except ValueError:
continue
else:
return self.ObjectToItem(g)
def GetValue(self, item, col):
node = self.ItemToObject(item)
if isinstance(node, Container):
mapper = { 0 : node.name,
1 : '',
}
return mapper[col]
elif isinstance(node, Element):
mapper = { 0 : node.name,
1 : node.len
}
return mapper[col]
else:
raise RuntimeError("unknown node type")
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Table")
panel = wx.Panel(self)
dvcTree = dv.DataViewCtrl(panel,style=wx.BORDER_THEME|dv.DV_MULTIPLE)
self.model = MyTreeListModel(data)
dvcTree.AssociateModel(self.model)
dvcTree.AppendTextColumn("Container", 0, width=80)
dvcTree.AppendTextColumn("Element", 1, width=80)
dvcTree.Bind(dv.EVT_DATAVIEW_ITEM_BEGIN_DRAG, self._onDrag)
dvcTree.Bind(dv.EVT_DATAVIEW_ITEM_DROP, self._onEndDrag)
dvcTree.Bind(dv.EVT_DATAVIEW_ITEM_DROP_POSSIBLE, self._onDropPossible)
self.dvcTree = dvcTree
dvcTree.EnableDragSource(wx.DataFormat(wx.DF_UNICODETEXT))
dvcTree.EnableDropTarget(wx.DataFormat(wx.DF_UNICODETEXT))
box = wx.BoxSizer(wx.VERTICAL)
box.Add(dvcTree, 1, wx.EXPAND)
panel.SetSizer(box)
self.Layout()
def _onDropPossible(self, evt):
item = evt.GetItem()
mod = evt.GetModel()
if not evt.GetItem().IsOk():
return
def _onEndDrag(self, evt):
if not evt.GetItem().IsOk():
evt.Veto()
return
mod = evt.GetModel()
print('dropped at', mod.ItemToObject(evt.GetItem()))
try:
print('parent:',mod.ItemToObject(mod.GetParent(evt.GetItem())))
except TypeError:
print('parent: None')
def _onDrag(self, evt):
evt.Allow()
mod = evt.GetModel()
print('from', mod.GetValue(evt.GetItem(),0))
evt.SetDataObject(wx.TextDataObject('don\'t know how to retrieve that information in the drop handler'))
evt.SetDragFlags(wx.Drag_AllowMove)
data = [Container('eins'),Container('zwei'),Container('drei')]
for d in data:
d[:] = [Element('element {}'.format('X'*q)) for q in range(5)]
if __name__ == "__main__":
app = wx.App()
f = MyFrame(None)
f.Show()
app.MainLoop()
EDIT:
This is mostly a problem on OSX since the MSW implementation does not offer to drop between lines. I was not able to test it on linux though.

Categories

Resources