Iterate QTreeView Rows - python

How would i modify the function below to properly iterate through just the rows in my QTreeview and not each row and each column?
While iterating through each row, I want to get the UserRole and DisplayRole data of the second column.
I'm close on the iteration part, but im not sure how to access UserRole and Display Role of the second column.
import sys, random
from PySide import QtGui, QtCore
class Browser(QtGui.QDialog):
def __init__(self, parent=None):
super(Browser, self).__init__(parent)
self.resize(300, 400)
self.uiItems = QtGui.QTreeView()
self.uiItems.setAlternatingRowColors(True)
self.uiItems.setSortingEnabled(True)
self.uiItems.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.uiItems.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.proxyModel = QtGui.QSortFilterProxyModel()
self.proxyModel.setSourceModel(QtGui.QStandardItemModel())
self.proxyModel.setDynamicSortFilter(True)
self.uiItems.setModel(self.proxyModel)
self.button = QtGui.QPushButton('Print')
grid = QtGui.QVBoxLayout(self)
grid.addWidget(self.uiItems)
grid.addWidget(self.button)
self.populate()
self.button.clicked.connect(self.printData)
def populate(self):
items = ['Cookie','Hummus','Spaghetti','Candy','Chocolate']
subitems = ['Sweet','Caramel','Sucker','Apple']
model = self.proxyModel.sourceModel()
model.clear()
model.setHorizontalHeaderLabels(['Name', 'Count'])
for item in items:
count = random.randint(0,3)
col1 = QtGui.QStandardItem(item)
# col2 = QtGui.QStandardItem(str(count))
# subitems:
for i in range(count):
child1 = QtGui.QStandardItem(subitems[random.randint(0,3)])
child2 = QtGui.QStandardItem(str(random.randint(0,20)))
col1.appendRow([child1, child2])
model.appendRow([col1])
self.uiItems.expandAll()
self.uiItems.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)
def iterItems(self, root):
if root is not None:
stack = [root]
while stack:
parent = stack.pop(0)
for row in range(parent.rowCount()):
for column in range(parent.columnCount()):
child = parent.child(row, column)
yield child
if child and child.hasChildren():
stack.append(child)
def printData(self):
for x in self.iterItems(self.proxyModel.sourceModel().invisibleRootItem()):
print x
def main():
app = QtGui.QApplication(sys.argv)
ex = Browser()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

def iterItems(self, root):
if root is not None:
for row in range(root.rowCount()):
row_item = root.child(row, 0)
if row_item.hasChildren():
for childIndex in range(row_item.rowCount()):
# Take second column from "child"-row
child = row_item.child(childIndex, 1)
yield child
def printData(self):
for x in self.iterItems(self.proxyModel.sourceModel().invisibleRootItem()):
print x.data(role=QtCore.Qt.DisplayRole), x.data(role=QtCore.Qt.UserRole)

If it works for you, a QTreeWidgetItemIterator might be much easier:
def iterTreeItems(tree)
iterator = QtWidgets.QTreeWidgetItemIterator(tree)
item: QtWidgets.QTreeWidgetItem = iterator.value()
while item is not None:
yield item
iterator += 1
item = iterator.value()

Related

Custom proxy model crashes when `removeRows()` from the source model

I am learning how to use proxy models recently, And I want to create a custom proxy model that can flat nodes in a source tree model to a list model, I have found a good solution to this:
How to create a proxy model that would flatten nodes of a QAbstractItemModel into a list in PySide?
However, when I try to removeRows() (remove tree node) from the source tree model, the proxy model crashes, I guess it's because the source model didn't emit layoutChanged signal to the proxy model to refresh the self.m_rowMap and self.m_indexMap?
【question1】: How to fix the crash?
【question2】:For QSortFilterProxyModel, removeRows() from the source model won't crash the proxy model, so I also want to know the underlying mechanism of QSortFilterProxyModel, especially the implementation of the following methods:
setSourceModel(),
mapFromSource(),
mapToSource(),
mapSelectionFromSource(),
mapSelectionToSource()
Especially how it emits signals between the sourceModel and the QSortFilterProxyModel?
Reproduce example:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import (QAbstractProxyModel, QModelIndex, pyqtSlot)
class FlatProxyModel(QAbstractProxyModel):
def __init__(self, parent=None):
# super(FlatProxyModel, self).__init__(parent)
super().__init__(parent)
def buildMap(self, model, parent=QModelIndex(), row=0):
"""
Usage:
* to build the rowMap and indexMap of the treeModel
"""
if row == 0:
self.m_rowMap = {}
self.m_indexMap = {}
rows = model.rowCount(parent)
for r in range(rows):
index = model.index(r, 0, parent)
print('row', row, 'item', model.data(index))
self.m_rowMap[index] = row
self.m_indexMap[row] = index
row = row + 1
if model.hasChildren(index):
row = self.buildMap(model, index, row)
return row
def setSourceModel(self, model):
QAbstractProxyModel.setSourceModel(self, model)
self.buildMap(model)
print(flush=True)
model.dataChanged.connect(self.sourceDataChanged)
def mapFromSource(self, index):
if index not in self.m_rowMap:
return QModelIndex()
# print('mapping to row', self.m_rowMap[index], flush = True)
return self.createIndex(self.m_rowMap[index], index.column())
def mapToSource(self, index):
if not index.isValid() or (index.row() not in self.m_indexMap):
return QModelIndex()
# print('mapping from row', index.row(), flush = True)
return self.m_indexMap[index.row()]
def columnCount(self, parent):
return QAbstractProxyModel.sourceModel(self).columnCount(self.mapToSource(parent))
def rowCount(self, parent):
# print('rows:', len(self.m_rowMap), flush=True)
return len(self.m_rowMap) if not parent.isValid() else 0
def index(self, row, column, parent):
# print('index for:', row, column, flush=True)
if parent.isValid():
return QModelIndex()
return self.createIndex(row, column)
def parent(self, index):
return QModelIndex()
#pyqtSlot(QModelIndex, QModelIndex)
def sourceDataChanged(self, topLeft, bottomRight):
self.dataChanged.emit(self.mapFromSource(topLeft),
self.mapFromSource(bottomRight))
class myWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.model = QtGui.QStandardItemModel()
names = ['Foo', 'Bar', 'Baz']
for first in names:
row = QtGui.QStandardItem(first)
for second in names:
row.appendRow(QtGui.QStandardItem(first + second))
self.model.appendRow(row)
self.proxy = FlatProxyModel()
self.proxy.setSourceModel(self.model)
self.nestedProxy = FlatProxyModel()
self.nestedProxy.setSourceModel(self.proxy)
vLayout = QtWidgets.QVBoxLayout(self)
hLayout = QtWidgets.QHBoxLayout()
self.treeView = QtWidgets.QTreeView()
self.treeView.setModel(self.model)
self.treeView.expandAll()
self.treeView.header().hide()
hLayout.addWidget(self.treeView)
self.listView1 = QtWidgets.QListView()
self.listView1.setModel(self.proxy)
hLayout.addWidget(self.listView1)
self.listView2 = QtWidgets.QListView()
self.listView2.setModel(self.nestedProxy)
hLayout.addWidget(self.listView2)
vLayout.addLayout(hLayout)
removeButton = QtWidgets.QPushButton('Remove')
removeButton.clicked.connect(self.removeItems)
vLayout.addWidget(removeButton)
def removeItems(self):
index = self.treeView.currentIndex()
model = index.model()
model.removeRows(index.row(), 1, index.parent())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = myWidget()
w.show()
sys.exit(app.exec_())
The problem is that when removing an item from the source model the proxy is not notified and the "map" is not updated. One possible solution is to connect the rowsRemoved signal to the buildMap.
class FlatProxyModel(QAbstractProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self.connections = []
def buildMap(self, model, parent=QModelIndex(), row=0):
# ...
def setSourceModel(self, model):
if self.sourceModel() is not None:
for connection in self.connections:
self.sourceModel().disconnect(connection)
QAbstractProxyModel.setSourceModel(self, model)
if self.sourceModel() is None:
self.connections = []
return
self.connections = [
self.sourceModel().dataChanged.connect(self.sourceDataChanged),
self.sourceModel().rowsRemoved.connect(self.reload_model),
self.sourceModel().modelReset.connect(self.reload_model),
self.sourceModel().rowsInserted.connect(self.reload_model)
]
self.reload_model()
def reload_model(self):
self.beginResetModel()
self.buildMap(self.sourceModel())
self.endResetModel()
# ...
def removeItems(self):
index = self.treeView.currentIndex()
if not index.isValid():
return
model = index.model()
model.removeRows(index.row(), 1, index.parent())

How to have multiple columns in a QComboBox with a QAbstractTableModel

I've seen questions similar to this one but they are aimed at QTableView. This is not using that,, this is just for a dropdown (QComboBox) with a custom QAbstractTableModel, which needs to have 2 columns.
BIG UPDATE
(Note: Legacy code has been deleted as this is a better approach on the same question, and legacy code was confusing as hell).
Okay, so trying to catch up with what #eyllanesc explained, I changed this from a QAbstractListModel to a QAbstractTableModel. The result is:
class ModelForComboboxesWithID(QAbstractTableModel):
"""Create our basic model"""
def __init__(self, program, records):
super(ModelForComboboxesWithID, self).__init__()
self._data = records
self.program = program
self.path_images = program.PATH_IMAGES
def rowCount(self, index: int = 0) -> int:
"""The length of the outer list. Structure: [row, row, row]"""
if not self._data:
return 0 # Doubt: Do we need to return this if self._data is empty?
return len(self._data)
def columnCount(self, index: int = 0) -> int:
"""The length of the sub-list inside the outer list. Meaning that Columns are inside rows
Structure: [row [column], row [column], row [column]]"""
if not self._data:
return 0 # Doubt: Do we need to return this if self._data is empty?
return len(self._data[0])
def data(self, index, role=None):
"""return the data on this index as data[row][column]"""
# 1 - Display data based on its content (this edits the text that you visually see)
if role == Qt.DisplayRole:
value = self._data[index.row()][index.column()]
return value
# 2 - Tooltip displayed when hovering on it
elif role == Qt.ToolTipRole:
return f"ID: {self._data[index.row()][1]}"
Which I set this way:
def eventFilter(self, target, event: QEvent):
if event.type() == QEvent.MouseButtonPress:
if target == self.Buscadorcombo_cliente:
records = ... # my query to the database
set_combo_records_with_ids(self.program, target, records)
target.currentIndexChanged.connect(self.test)
def set_combo_records_with_ids(program, combobox: QComboBox, records):
"""Clear combobox, set model/data and sort it"""
combobox.clear()
model = ModelForComboboxesWithID(program, records)
combobox.setModel(model)
combobox.model().sort(0, Qt.AscendingOrder)
combobox.setModelColumn(0)
The result of this works almost perfect:
On the dropdown(Combobox) it displays the name.
If you hover on an item, it displays the ID.
Now I am able to get any data of it this way.
def test(self, index):
data_id = self.Buscadorcombo_cliente.model().index(index, 1).data()
data_name = self.Buscadorcombo_cliente.model().index(index, 0).data()
print(data_id)
print(data_name)
You have to set a QTableView as a view:
from PySide2 import QtGui, QtWidgets
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
combo = QtWidgets.QComboBox()
model = QtGui.QStandardItemModel(0, 2)
for i in range(10):
items = []
for j in range(model.columnCount()):
it = QtGui.QStandardItem(f"it-{i}{j}")
items.append(it)
model.appendRow(items)
combo.setModel(model)
view = QtWidgets.QTableView(
combo, selectionBehavior=QtWidgets.QAbstractItemView.SelectRows
)
combo.setView(view)
view.verticalHeader().hide()
view.horizontalHeader().hide()
header = view.horizontalHeader()
for i in range(header.count()):
header.setSectionResizeMode(i, QtWidgets.QHeaderView.Stretch)
lay = QtWidgets.QVBoxLayout(w)
lay.addWidget(combo)
lay.addStretch()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

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_())

Single column QTreeview search filter

I have two questions:
I was wondering if this is the proper way to do a search/filter on a single column treeview. I feel like a lot of my copying/pasting could contain unnecessary stuff. Is all the code in the subclass of QSortFilterProxyModel and the code in the search_text_changed method needed? I don't feel like the regex is needed, since I set the filter-proxy to ignore case-sensitivity.
How can I make it so that when a user double-clicks a treeview item a signal emits a string list containing the string of the item clicked and all of its ancestors recursively? For example, if I double-clicked "Birds", it would return ['Birds','Animals']; and if I double-clicked "Animals", it would just return ['Animals'].
import os, sys
from PySide import QtCore, QtGui
tags = {
"Animals": [
"Birds",
"Various"
],
"Brick": [
"Blocks",
"Special"
],
"Manmade": [
"Air Conditioners",
"Audio Equipment"
],
"Food": [
"Fruit",
"Grains and Seeds"
]
}
class SearchProxyModel(QtGui.QSortFilterProxyModel):
def __init__(self, parent=None):
super(SearchProxyModel, self).__init__(parent)
self.text = ''
# Recursive search
def _accept_index(self, idx):
if idx.isValid():
text = idx.data(role=QtCore.Qt.DisplayRole).lower()
condition = text.find(self.text) >= 0
if condition:
return True
for childnum in range(idx.model().rowCount(parent=idx)):
if self._accept_index(idx.model().index(childnum, 0, parent=idx)):
return True
return False
def filterAcceptsRow(self, sourceRow, sourceParent):
# Only first column in model for search
idx = self.sourceModel().index(sourceRow, 0, sourceParent)
return self._accept_index(idx)
def lessThan(self, left, right):
leftData = self.sourceModel().data(left)
rightData = self.sourceModel().data(right)
return leftData < rightData
class TagsBrowserWidget(QtGui.QWidget):
clickedTag = QtCore.Signal(list)
def __init__(self, parent=None):
super(TagsBrowserWidget, self).__init__(parent)
self.resize(300,500)
# controls
self.ui_search = QtGui.QLineEdit()
self.ui_search.setPlaceholderText('Search...')
self.tags_model = SearchProxyModel()
self.tags_model.setSourceModel(QtGui.QStandardItemModel())
self.tags_model.setDynamicSortFilter(True)
self.tags_model.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.ui_tags = QtGui.QTreeView()
self.ui_tags.setSortingEnabled(True)
self.ui_tags.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.ui_tags.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.ui_tags.setHeaderHidden(True)
self.ui_tags.setRootIsDecorated(True)
self.ui_tags.setUniformRowHeights(True)
self.ui_tags.setModel(self.tags_model)
# layout
main_layout = QtGui.QVBoxLayout()
main_layout.addWidget(self.ui_search)
main_layout.addWidget(self.ui_tags)
self.setLayout(main_layout)
# signals
self.ui_tags.doubleClicked.connect(self.tag_double_clicked)
self.ui_search.textChanged.connect(self.search_text_changed)
# init
self.create_model()
def create_model(self):
model = self.ui_tags.model().sourceModel()
self.populate_tree(tags, model.invisibleRootItem())
self.ui_tags.sortByColumn(0, QtCore.Qt.AscendingOrder)
def populate_tree(self, children, parent):
for child in sorted(children):
node = QtGui.QStandardItem(child)
parent.appendRow(node)
if isinstance(children, dict):
self.populate_tree(children[child], node)
def tag_double_clicked(self, item):
text = item.data(role=QtCore.Qt.DisplayRole)
print [text]
self.clickedTag.emit([text])
def search_text_changed(self, text=None):
regExp = QtCore.QRegExp(self.ui_search.text(), QtCore.Qt.CaseInsensitive, QtCore.QRegExp.FixedString)
self.tags_model.text = self.ui_search.text().lower()
self.tags_model.setFilterRegExp(regExp)
if len(self.ui_search.text()) >= 1 and self.tags_model.rowCount() > 0:
self.ui_tags.expandAll()
else:
self.ui_tags.collapseAll()
def main():
app = QtGui.QApplication(sys.argv)
ex = TagsBrowserWidget()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
There's no point in setting the case-sensivity of the filter-proxy at all, because you are by-passing the built-in filtering by overriding filterAcceptsRow. And even if you weren't doing that, setFilterRegExp ignores the current case sensitiviy settings anyway.
I would simplify the filter-proxy to this:
class SearchProxyModel(QtGui.QSortFilterProxyModel):
def setFilterRegExp(self, pattern):
if isinstance(pattern, str):
pattern = QtCore.QRegExp(
pattern, QtCore.Qt.CaseInsensitive,
QtCore.QRegExp.FixedString)
super(SearchProxyModel, self).setFilterRegExp(pattern)
def _accept_index(self, idx):
if idx.isValid():
text = idx.data(QtCore.Qt.DisplayRole)
if self.filterRegExp().indexIn(text) >= 0:
return True
for row in range(idx.model().rowCount(idx)):
if self._accept_index(idx.model().index(row, 0, idx)):
return True
return False
def filterAcceptsRow(self, sourceRow, sourceParent):
idx = self.sourceModel().index(sourceRow, 0, sourceParent)
return self._accept_index(idx)
and change the search method to this:
def search_text_changed(self, text=None):
self.tags_model.setFilterRegExp(self.ui_search.text())
if len(self.ui_search.text()) >= 1 and self.tags_model.rowCount() > 0:
self.ui_tags.expandAll()
else:
self.ui_tags.collapseAll()
So now the SearchProxyModel has sole responsibilty for deciding how searches are performed via its setFilterRegExp method. The case-sensitivity is handled transparently, so there is no need to pre-process the input.
The method for getting a list of descendants, can be written like this:
def tag_double_clicked(self, idx):
text = []
while idx.isValid():
text.append(idx.data(QtCore.Qt.DisplayRole))
idx = idx.parent()
text.reverse()
self.clickedTag.emit(text)

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_())

Categories

Resources