49 lines
1.2 KiB
Python
49 lines
1.2 KiB
Python
from collections import defaultdict
|
|
from PyQt5.QtWidgets import QListWidget, QListWidgetItem
|
|
|
|
|
|
class DictList(QListWidget):
|
|
|
|
def __init__(self, data, *args, factory=list, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.data = defaultdict(factory)
|
|
self.update(data)
|
|
|
|
def update(self, data):
|
|
for k, v in data.items():
|
|
self.add(k, v)
|
|
|
|
def add(self, key, value):
|
|
self.prepend_item_if_missing(key)
|
|
self.data[key] = value
|
|
|
|
def append(self, key, value):
|
|
self.prepend_item_if_missing(key)
|
|
self.data[key].append(value)
|
|
|
|
def prepend_item_if_missing(self, key):
|
|
if key not in self.data:
|
|
itm = QListWidgetItem(key)
|
|
self.prependItem(itm)
|
|
|
|
def prependItem(self, itm):
|
|
self.insertItem(0, itm)
|
|
|
|
def get(self, index):
|
|
key = self.get_key(index)
|
|
value = self.data[key]
|
|
return key, value
|
|
|
|
def get_value(self, index):
|
|
_key, value = self.get(index)
|
|
return value
|
|
|
|
def get_key(self, index): # this relies on dict being ordered
|
|
lst = list(self.data)
|
|
lst.reverse() # add prepends the new items
|
|
row = index.row()
|
|
return lst[row]
|
|
|
|
|
|
|