I am trying to create a QTableView in Qt which is efficient for large tables. I've managed to make the display of data efficient by defining my own abstract table model:
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
class DataTableModel(QtCore.QAbstractTableModel):
def columnCount(self, index=None):
return 3
def rowCount(self, index=None):
return 10000
def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return None
if orientation == Qt.Horizontal:
return 'c'
elif orientation == Qt.Vertical:
return 'r'
def data(self, index, role):
if not index.isValid():
return None
if role == Qt.DisplayRole:
return "({0},{1})".format(index.row(), index.column())
app = QtGui.QApplication([""])
viewer = QtGui.QTableView()
model = DataTableModel()
viewer.setModel(model)
viewer.show()
This works fine, because the data method is only called for cells that appear in the field of view of the table.
I now want to display an existing selection of some fraction of the rows:
import numpy as np
selected_rows = np.where(np.random.random(10000) > 0.5)[0]
I can tell the table widget about this selection by doing e.g.:
smodel = viewer.selectionModel()
for row in selected_rows:
model_index = model.createIndex(row, 0)
smodel.select(model_index, QtGui.QItemSelectionModel.Select | QtGui.QItemSelectionModel.Rows)
However, this is very inefficient. It typically takes a second to select 1000-2000 rows, when in practice I have tables with millions of rows. There may be ways of speeding up this loop, but I would like to do away with the loop altogether, and instead have Qt only ask me (similarly to the data itself) for information about selections within the visible cells. Is this possible, and if so, what is the best way to achieve this?
You should use the second overloaded version of select, the one that accepts a QItemSelection instead of a single index.
The QItemSelection is able to select ranges of rows by providing the two argument to the constructor:
QItemSelection(start_index, stop_index)
moreover you can merge the items to become a single selection:
selection.merge(other_selection, flags)
This suggest to:
Sort the indices of the rows you want to select
Use itertools.groupby to group together consecutive rows
Use createIndex to get the QModelIndex of all start-end indices of these groups
Create the QItemSelection objects for each group of rows
merge all QItemSelections into a single QItemSelection
Perform the selection over your model.
Note that you want to sort the rows by index, not by their values.
The simplest way would be to reimplement the selection model. The view queries the selection model for the selection status of each index. Alas, the QItemSelectionModel has a major shortcoming: you can't reimplement its isSelected method.
The best you can do is to create a fresh selection model on a model perhaps not attached to any views, then to select the items there, and finally to set the model and selection model on the view.
This is an API shortcoming.
If this is a professional project, you should be compiling your own copy of Qt anyway, under your own git version control, and it's a trivial manner to make the isSelected method virtual.
If you want to display some selected rows only as opposite to
display everything and select some rows, then QSortFilterProxyModel could help:
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
import numpy as np
class FilterProxy(QtGui.QSortFilterProxyModel):
afilter = set(np.where(np.random.random(10000) > 0.5)[0])
def updateFilter(self, new_filter):
self.afilter = new_filter
self.invalidateFilter()
def filterAcceptsRow(self, row, parent):
if not self.afilter:
return True
return row in self.afilter
class DataTableModel(QtCore.QAbstractTableModel):
def columnCount(self, index=None):
return 3
def rowCount(self, index=None):
return 10000
def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return None
if orientation == Qt.Horizontal:
return 'c'
elif orientation == Qt.Vertical:
return 'r'
def data(self, index, role):
if not index.isValid():
return None
if role == Qt.DisplayRole:
return "({0},{1})".format(index.row(), index.column())
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.viewer = QtGui.QTableView()
self.setCentralWidget(self.viewer)
self.action = QtGui.QAction("Filter x > 0.5", self)
self.action.triggered.connect(self.updateFilter)
self.addToolBar("Ffilter").addAction(self.action)
self.model = DataTableModel()
self.proxyModel = FilterProxy(self.viewer)
self.proxyModel.setDynamicSortFilter(True)
self.proxyModel.setSourceModel(self.model)
self.viewer.setModel(self.proxyModel)
def updateFilter(self):
new_max = np.random.rand(1)[0]
new_filter = set(np.where(np.random.random(10000) > new_max)[0])
self.action.setText("Filter x > {} N = {}".format(new_max, len(new_filter)))
self.proxyModel.updateFilter(new_filter)
app = QtGui.QApplication([""])
viewer = MyWindow()
viewer.show()
app.exec_()
Related
I am trying to set up a simple QTreeView with nice columns. The first two columns are set to fit the contents, the last column is set to stretch.
For some reason, the minimum width of the last column ("Balance") is way higher than it needs to be, which produces unwanted behaviour. I captured this behavior on this video (YouTube link). The last column takes way too much space and does not shrink as much as it should when the QWidget is shrunk.
The complete code producing this example is below. I am aware the QAbstractItemModel is implemented incorrectly but it is a minimal implementation that showcases the issue.
I tried playing around with QTreeView.header().setMinimumWidth(0) but that did not work either.
I don't understand where is the issue because I think the MRE below is already very barebones and nearly all settings are left to default values. Why would the column which has ResizeMode.Stretch need to take up so much minimum width? Shouldn't it take at maximum the width of the header text, i.e. "Balance"? It seems to take up roughly twice as much.
I am running Python 3.11.2 and PyQt 6.4.2.
MRE:
import sys
from typing import Any
from PyQt6 import QtWidgets
from PyQt6.QtCore import QAbstractItemModel, QModelIndex, Qt
from PyQt6.QtWidgets import QApplication, QHeaderView, QTreeView, QWidget
class Form(QWidget):
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent=parent)
self.resize(323, 454)
self.horizontalLayout = QtWidgets.QHBoxLayout(self)
self.horizontalLayout.setObjectName("horizontalLayout")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout.addLayout(self.verticalLayout)
self.treeView = QTreeView(self)
self.verticalLayout.addWidget(self.treeView)
self.treeView.setModel(CategoryTreeModel(self.treeView))
self.treeView.header().setSectionResizeMode(
0,
QHeaderView.ResizeMode.ResizeToContents,
)
self.treeView.header().setSectionResizeMode(
1,
QHeaderView.ResizeMode.ResizeToContents,
)
self.treeView.header().setSectionResizeMode(
2,
QHeaderView.ResizeMode.Stretch,
)
class CategoryTreeModel(QAbstractItemModel):
COLUMN_HEADERS = {
0: "Name",
1: "Transactions",
2: "Balance",
}
def __init__(
self,
tree_view: QTreeView,
) -> None:
super().__init__()
self._tree_view = tree_view
def rowCount(self, index: QModelIndex = ...) -> int:
return 5
def columnCount(self, index: QModelIndex = ...) -> int: # noqa: U100
return 3
def index(self, row: int, column: int, _parent: QModelIndex = ...) -> QModelIndex:
return QAbstractItemModel.createIndex(self, row, column, "item")
def parent(self, index: QModelIndex = ...) -> QModelIndex:
return QModelIndex()
def data(self, index: QModelIndex, role: Qt.ItemDataRole = ...) -> Any:
if not index.isValid():
return None
column = index.column()
if role == Qt.ItemDataRole.DisplayRole:
if column == 0:
return "some very long name"
if column == 1:
return "0"
if column == 2:
return "0"
return None
def headerData(
self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole = ...
) -> str | int | None:
if role == Qt.ItemDataRole.TextAlignmentRole:
if section == 2:
return Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter
if role == Qt.ItemDataRole.DisplayRole:
if orientation == Qt.Orientation.Horizontal:
return self.COLUMN_HEADERS[section]
return str(section)
return None
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec()
The documentation is a bit obscure on the point, and it requires considering multiple aspects:
the stretchLastSection() tells if the last header section takes all available space, and if it's set to True (which is the default value for QTreeView) it overrides the section resize mode of the last section;
when disabled, it uses the default value of sectionResizeMode() (which is Interactive and by default uses the defaultSectionSize() or that of the section;
the default sectionResizeMode() can only be changed using setSectionResizeMode(mode) (without any section reference);
This means that, if stretchLastSection() is True:
calling setSectionResizeMode(section, mode) is pointless for the last section;
it will always use the minimum size of the defaultSectionSize(), no matter if it could theoretically stretch the size of the section;
The basic solution, then, is to ensure that you call setStretchLastSection(False).
This will allow resizing the section to a point where the section text won't be readable, so you could also add the following:
style = self.style()
lastSectionText = self.treeView.model().headerData(
2, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or 'XXXX'
self.treeView.header().setMinimumSectionSize(
style.pixelMetric(style.PixelMetric.PM_HeaderMarkSize)
+ style.pixelMetric(style.PixelMetric.PM_HeaderGripMargin) * 2
+ self.fontMetrics().horizontalAdvance(lastSectionText)
)
For obvious reasons, the code right above might not work fine if you use setSectionsMovable(True), or if the resize modes or section text change at runtime. In that case, you may need to create your own QHeaderView subclass.
Note: the ifs in headerData() are not optimal, since they will all be performed whenever the orientation is vertical: use elif instead for the main indentation (the if role); also, return None is implicit for return and when the function exits normally, so just use return when you want to return None and skip the last one.
I am using PyQt5 to make an application. One of my widgets will be a QListView that displays a list of required items, e.g. required to cook a particular dish, say.
For most of these, the listed item is the only possibility. But for a few items, there is more than one option that will fulfill the requirements. For those with multiple possibilities, I want to display those possibilities in a functional QComboBox. So if the user has no whole milk, they can click that item, and see that 2% milk also works.
How can I include working combo boxes among the elements of my QListView?
Below is an example that shows what I have so far. It can work in Spyder or using python -i, you just have to comment or uncomment as noted. By "work", I mean it shows the required items in QListView, but the combo boxes show only the first option, and their displays can't be changed with the mouse. However, I can say e.g. qb1.setCurrentIndex(1) at the python prompt, and then when I move the mouse pointer onto the widget, the display updates to "2% milk". I have found it helpful to be able to interact with and inspect the widget in Spyder or a python interpreter, but I still have this question. I know there are C++ examples of things like this around, but I have been unable to understand them well enough to do what I want. If we can post a working Python example of this, it will help me and others too I'm sure.
from PyQt5.QtWidgets import QApplication, QComboBox, QListView, QStyledItemDelegate
from PyQt5.QtCore import QAbstractListModel, Qt
# A delegate for the combo boxes.
class QBDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
painter.drawText(option.rect, Qt.AlignLeft, self.parent().currentText())
# my own wrapper for the abstract list class
class PlainList(QAbstractListModel):
def __init__(self, elements):
super().__init__()
self.elements = elements
def data(self, index, role):
if role == Qt.DisplayRole:
text = self.elements[index.row()]
return text
def rowCount(self, index):
try:
return len(self.elements)
except TypeError:
return self.elements.rowCount(index)
app = QApplication([]) # in Spyder, this seems unnecessary, but harmless.
qb0 = 'powdered sugar' # no other choice
qb1 = QComboBox()
qb1.setModel(PlainList(['whole milk','2% milk','half-and-half']))
d1 = QBDelegate(qb1)
qb1.setItemDelegate(d1)
qb2 = QComboBox()
qb2.setModel(PlainList(['butter', 'lard']))
d2 = QBDelegate(qb2)
qb2.setItemDelegate(d2)
qb3 = 'cayenne pepper' # there is no substitute
QV = QListView()
qlist = PlainList([qb0, qb1, qb2, qb3])
QV.setModel(qlist)
QV.setItemDelegateForRow(1, d1)
QV.setItemDelegateForRow(2, d2)
QV.show()
app.exec_() # Comment this line out, to run in Spyder. Then you can inspect QV etc in the iPython console. Handy!
There are some misconceptions in your attempt.
First of all, setting the delegate parent as a combo box and then setting the delegate for the list view won't make the delegate show the combo box.
Besides, as the documentation clearly says:
Warning: You should not share the same instance of a delegate between views. Doing so can cause incorrect or unintuitive editing behavior since each view connected to a given delegate may receive the closeEditor() signal, and attempt to access, modify or close an editor that has already been closed.
In any case, adding the combo box to the item list is certainly not an option: the view won't have anything to do with it, and overriding the data() to show the current combo item is not a valid solution; while theoretically item data can contain any kind of object, for your purpose the model should contain data, not widgets.
In order to show a different widget for a view, you must override createEditor() and return the appropriate widget.
Then, since you probably need to keep the data available when accessing the model and for the view, the model should contain the available options and eventually return the current option or the "sub-list" depending on the situation.
Finally, rowCount() must always return the row count of the model, not that of the content of the index.
A possibility is to create a "nested model" that supports a "current index" for the selected option for inner models.
Then you could either use openPersistentEditor() or implement flags() and add the Qt.ItemIsEditable for items that contain a list model.
class QBDelegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
value = index.data(Qt.EditRole)
if isinstance(value, PlainList):
editor = QComboBox(parent)
editor.setModel(value)
editor.setCurrentIndex(value.currentIndex)
# submit the data whenever the index changes
editor.currentIndexChanged.connect(
lambda: self.commitData.emit(editor))
else:
editor = super().createEditor(parent, option, index)
return editor
def setModelData(self, editor, model, index):
if isinstance(editor, QComboBox):
# the default implementation tries to set the text if the
# editor is a combobox, but we need to set the index
model.setData(index, editor.currentIndex())
else:
super().setModelData(editor, model, index)
class PlainList(QAbstractListModel):
currentIndex = 0
def __init__(self, elements):
super().__init__()
self.elements = []
for element in elements:
if isinstance(element, (tuple, list)) and element:
element = PlainList(element)
self.elements.append(element)
def data(self, index, role=Qt.DisplayRole):
if role == Qt.EditRole:
return self.elements[index.row()]
elif role == Qt.DisplayRole:
value = self.elements[index.row()]
if isinstance(value, PlainList):
return value.elements[value.currentIndex]
else:
return value
def flags(self, index):
flags = super().flags(index)
if isinstance(index.data(Qt.EditRole), PlainList):
flags |= Qt.ItemIsEditable
return flags
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.EditRole:
item = self.elements[index.row()]
if isinstance(item, PlainList):
item.currentIndex = value
else:
self.elements[index.row()] = value
return True
def rowCount(self, parent=None):
return len(self.elements)
app = QApplication([])
qb0 = 'powdered sugar' # no other choice
qb1 = ['whole milk','2% milk','half-and-half']
qb2 = ['butter', 'lard']
qb3 = 'cayenne pepper' # there is no substitute
QV = QListView()
qlist = PlainList([qb0, qb1, qb2, qb3])
QV.setModel(qlist)
QV.setItemDelegate(QBDelegate(QV))
## to always display the combo:
#for i in range(qlist.rowCount()):
# index = qlist.index(i)
# if index.flags() & Qt.ItemIsEditable:
# QV.openPersistentEditor(index)
QV.show()
app.exec_()
I want a drop-down category selection box which allows the user to click multiple selections, and which preferably is connected to an SQL query. I'm not attached to the Combobox in particular (disappearing on each click isn't helpful), whatever can get the job done.
At the current moment, I have basically that jerry-rigged together, it allows for multiple selections technically but it's just based on randomly if the mouse is dragged over it or not.
self.catbx=QComboBox()
...
self.catq=QtSql.QSqlQuery(conn)
self.catq.exec("SELECT name FROM categories")
self.catmo=QtSql.QSqlQueryModel()
self.catmo.setQuery(self.catq)
self.catbx.setModel(self.catmo)
...
self.catview=QListView()
self.catview.setModel(self.catmo)
self.catbx.setView(self.catview)
self.catview.setSelectionMode(QAbstractItemView.MultiSelection)
hope that's clear enough and someone can help! :)
Basically it is that the items are not selectable, since that is the event that triggers the closing of the popup so the solution is to eliminate that flag in the model as I did in a previous answer.
On the other hand the option to be checkeable does not come by default in the QSqlQueryModel, so we have to implement it for that we based on another previous answer.
Finally, a class is created that inherits from QComboBox and we overwrite the hidePopup() method to emit a signal that sends the selected items.
Update:
If you want to also be marked when you press any part of the item you must create a delegate and overwrite the editorEvent() method so that it handles the MouseButtonRelease event. But this brings a small problem: to open the popup you have to press the item that is displayed so it will open marked.
from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
class CheckSqlQueryModel(QtSql.QSqlQueryModel):
def __init__(self, *args, **kwargs):
QtSql.QSqlQueryModel.__init__(self, *args, **kwargs)
self.checks = {}
def checkState(self, pindex):
if pindex not in self.checks.keys():
self.checks[pindex] = QtCore.Qt.Unchecked
return self.checks[pindex]
def data(self, index, role=QtCore.Qt.DisplayRole):
if role == QtCore.Qt.CheckStateRole and index.isValid():
return self.checkState(QtCore.QPersistentModelIndex(index))
return QtSql.QSqlQueryModel.data(self, index, role)
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.CheckStateRole and index.isValid():
self.checks[QtCore.QPersistentModelIndex(index)] = value
return True
return QtSql.QSqlQueryModel(self, index, value, role)
def flags(self, index):
fl = QtSql.QSqlQueryModel.flags(self, index) & ~QtCore.Qt.ItemIsSelectable
fl |= QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable
return fl
class CheckComboBox(QtWidgets.QComboBox):
selectedChanged = QtCore.pyqtSignal(list)
def hidePopup(self):
results = []
for i in range(self.count()):
if self.itemData(i, QtCore.Qt.CheckStateRole) == QtCore.Qt.Checked:
results.append(self.itemText(i))
self.selectedChanged.emit(results)
QtWidgets.QComboBox.hidePopup(self)
class CheckDelegate(QtWidgets.QStyledItemDelegate):
def editorEvent(self, event, model, option, index):
if event.type() == QtCore.QEvent.MouseButtonRelease:
val = index.data(QtCore.Qt.CheckStateRole)
new_val = QtCore.Qt.Checked if val == QtCore.Qt.Unchecked else QtCore.Qt.Unchecked
model.setData(index, new_val, QtCore.Qt.CheckStateRole)
return True
return QtWidgets.QStyledItemDelegate.editorEvent(self, event, model, option, index)
class Widget(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
QtWidgets.QWidget.__init__(self, *args, **kwargs)
lay = QtWidgets.QVBoxLayout(self)
combo = CheckComboBox()
combo.setView(QtWidgets.QListView())
combo.setItemDelegate(CheckDelegate(combo))
model = CheckSqlQueryModel()
model.setQuery("SELECT name FROM categories")
combo.setModel(model)
self.lw = QtWidgets.QListWidget()
combo.selectedChanged.connect(self.on_selectedChanged)
lay.addWidget(combo)
lay.addWidget(self.lw)
def on_selectedChanged(self, items):
self.lw.clear()
self.lw.addItems(items)
def createConnection():
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(":memory:")
if not db.open():
QtWidgets.QMessageBox.critical(None, "Cannot open database",
"Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information how "
"to build it.\n\n"
"Click Cancel to exit.", QMessageBox.Cancel)
return False
query = QtSql.QSqlQuery()
query.exec_("create table categories (id int primary key, name varchar(20))");
for i in range(1, 10):
query.exec_("insert into categories values({i}, 'categories-{i}')".format(i=i));
return True
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = Widget()
w.show()
sys.exit(app.exec_())
I would like to render each item in a QTreeView differently based on a number of attributes stored in a database and based on whether the item is a folder or a file. However, I don't understand how the QTreeView or QFileSystemModel communicate with the delegate. Whenever an item must be drawn, including during initialization, I'd expect to provide the delegate with all the parameters it requires and then use a series of if statements within the delegate to set how the particular item is drawn. I've only found the .setItemDelegate method and don't know when or how the delegate is actually called or how it loops through all the items in the model. Below is an example based on material online. There are two problems:
I placed code in comments that I was unable to get working. Once I understand how the delegate can receive information from the QTreeView (or calling class), I believe I can do the rest.
I was unable to get this subclass of the QTreeView to display the folder and file icons.
Code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class fileSystemDelegate(QItemDelegate):
def __init__(self, parent=None):
QItemDelegate.__init__(self, parent) #shouldn't this insure the icons are drawn?
def paint(self, painter, option, index):
painter.save()
# set background
painter.setPen(QPen(Qt.NoPen))
if option.state & QStyle.State_Selected: #DURING DRAW LOOP: idx = self.currentIndex(); if self.fileSystemModel.isDir(idx): PAINT RED
painter.setBrush(QBrush(Qt.red))
else:
painter.setBrush(QBrush(Qt.white)) #ELSE PAINT WHITE
painter.drawRect(option.rect)
# draw item
painter.setPen(QPen(Qt.black))
text = index.data(Qt.DisplayRole)
painter.drawText(option.rect, Qt.AlignLeft, text) #there is no painter.drawIcon?
painter.restore()
class fileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)
delegate = fileSystemDelegate()
self.setItemDelegate(delegate) # how to provide delegate with additional info about the item to be drawn ?
self.fileSystemModel = QFileSystemModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = fileSystemBrowser()
window.show()
sys.exit(app.exec_())
EDIT 1:
I've added an example "database" in the form of a dictionary and changed the approach to rely on the data method rather than the delegate. I would expect this code to perform the dictionary lookup whenever information is displayed in the tree and therefore print to the terminal when the user enters C:\Program Files\Internet Explorer\ on a Microsoft Windows computer. However, it just displays the directory without printing anything to the terminal. I'd like to know:
How do I get if statements in the data method to trigger for every item in the display as they are being drawn?
How can I display an icon after the default icon is displayed, on the same row?
Code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
database = {'C:\Program Files\Internet Explorer\ExtExport.exe':(1,3), 'C:\Program Files\Internet Explorer\iexplore.exe':(0,0)}
class fileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)
self.fileSystemModel = QFileSystemModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
path = self.fileSystemModel.filePath(index)
if self.fileSystemModel.isDir(index):
if database.get(path) != None:
if database[path][0] > 0:
print("Acting on custom data 0.") # add another icon after the regular folder icon
if database[path][1] > 0:
print("Acting on custom data 1.") # add another (different) icon after the regular folder or previous icon
if __name__ == '__main__':
app = QApplication(sys.argv)
window = fileSystemBrowser()
window.show()
sys.exit(app.exec_())
EDIT 2:
Subclassing the model definitely did make a difference. Now the script appears to be calling my new data method on every item. Unfortunately, the data method doesn't work yet so the result is a treeview without icons or text. Sometimes I receive the error: "QFileSystemWatcher: failed to add paths: C:/PerfLogs". Based on examples online, I've commented where I think my errors may be, but I cannot yet get this to work. What am I doing wrong?
import sys
from PySide.QtCore import *
from PySide.QtGui import *
database = {'C:\Program Files\Internet Explorer\ExtExport.exe':(1,3), 'C:\Program Files\Internet Explorer\iexplore.exe':(0,0)}
class newFileModel(QFileSystemModel):
def __init__(self, parent=None):
QFileSystemModel.__init__(self, parent)
#self.elements = [[Do I need this? What should go here?]]
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
path = self.filePath(index)
if self.isDir(index):
if database.get(path) != None:
if database[path][0] > 0:
print("Acting on custom data 0.") # I can add code here for different color text, etc.
if database[path][1] > 0:
print("Acting on custom data 1.") # I'll add code later
#return self.data(index, role) # Do I need this about here?
class fileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)
self.fileSystemModel = newFileModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = fileSystemBrowser()
window.show()
sys.exit(app.exec_())
Here is a basic demo that shows how to add an extra column with icons and other formatting. Note that an attempt is made to normalise the file-paths so that comparisons and dictionary look-ups should be more reliable:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
database = {
QFileInfo('C:\Program Files\Internet Explorer\ExtExport.exe').absoluteFilePath(): (1, 3),
QFileInfo('C:\Program Files\Internet Explorer\iexplore.exe').absoluteFilePath(): (0, 0),
}
class FileSystemModel(QFileSystemModel):
def __init__(self, parent=None):
super().__init__(parent)
style = qApp.style()
self.icons = [
style.standardIcon(QStyle.SP_MessageBoxInformation),
style.standardIcon(QStyle.SP_MessageBoxWarning),
]
def columnCount(self, parent=QModelIndex()):
return super().columnCount(parent) + 1
def data(self, index, role=Qt.DisplayRole):
extra = False
if index.isValid():
extra = index.column() == self.columnCount(index.parent()) - 1
info = self.fileInfo(index)
path = info.absoluteFilePath()
if path in database:
major, minor = database[path]
print('found:', (major, minor), path)
if extra:
if role == Qt.DecorationRole:
if major > 0:
return self.icons[0]
else:
return self.icons[1]
elif role == Qt.DisplayRole:
return '%s/%s' % (major, minor)
elif role == Qt.ForegroundRole:
if minor > 2:
return QColor('red')
if not extra:
return super().data(index, role)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if (orientation == Qt.Horizontal and
role == Qt.DisplayRole and
section == self.columnCount() - 1):
return 'Extra'
return super().headerData(section, orientation, role)
class FileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)
self.fileSystemModel = FileSystemModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)
self.header().moveSection(self.fileSystemModel.columnCount() - 1, 1)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = FileSystemBrowser()
window.show()
sys.exit(app.exec_())
EDIT:
The roles used in the data method are all documented under the ItemDataRole enum, and are introduced as follows:
Each item in the model has a set of data elements associated with it,
each with its own role. The roles are used by the view to indicate to
the model which type of data it needs. Custom models should return
data in these types.
For the extra column that has been added, it is necessary to supply everything, because it is a virtual column that is not part of the underlying model. But for the other columns, we can just call the base-class implementation to get the default values (of course, if desired, we could also return custom values for these columns to modify the existing behaviour).
I've been following some tutorials and trying to get a list model set up. My main window has two list views that are accessing the same model. When I update an item in one list, the other list doesn't update itself until it gets focus (I click on it). So it looks like the dataChanged signal isn't being emitted, but I can't work out how my code is different to any of the examples I'm basing it from.
main.py
class Main(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.ui = uic.loadUi("mainwindow.ui", self)
# Test model and listviews
data = [10,20,30,40,50]
myModel = model.MyListModel(data)
self.ui.listView.setModel(myModel)
self.ui.listView_2.setModel(myModel)
model.py
class MyListModel(QtCore.QAbstractListModel):
def __init__(self, data=[], parent=None):
super(MyListModel, self).__init__(parent)
self.__data = data
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.__data)
def data(self, index, role=QtCore.Qt.DisplayRole):
row = index.row()
if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
return str(self.__data[row])
if role == QtCore.Qt.ToolTipRole:
return 'Item at {0}'.format(row)
def flags(self, index):
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
self.__data[index.row()] = value
self.dataChanged.emit(index, index)
return True
return False
Can anyone see what is wrong here? FYI I'm using PyQT5.2.1 and Python 3.3.
The problem is with the signature of dataChanged signal. In Qt4 it looked like this:
dataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight)
but in Qt5, it looks like this:
dataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight,
const QVector<int> & roles = QVector<int>())
when I tried your example code with PyQt-5.1.1, I got an error when attempting to emit the signal without the third argument. Strictly speaking, this was incorrect behaviour, because the third argument has a default value. So this is perhaps why the behaviour has changed.
But it seems that you must now explicitly emit an empty list as the third argument of dataChanged in order for things to work properly in PyQt5:
self.dataChanged.emit(index, index, [])
or, of course, emit a list of the roles that have actually been changed:
self.dataChanged.emit(index, index, [QtCore.Qt.EditRole])
The solution:
self.dataChanged.emit(index, index, ())
do not work for me (python 2.7, PyQt5).
But one of the following will work:
self.dataChanged.emit(index, index, [])
self.dataChanged.emit(index, index, list())