In PyQt I have a view with rows in it from a model (which in turn is from a SQLite…
- User
In PyQt I have a view with rows in it from a model (which in turn is from a SQLite database). I would like to get some of those rows, change the colour of them and display them in the view. Is there a Class that would help me in this? I am thinking I could get the rows from the original view, create another view with the rows and modify the rows as I'd like. Then a final need is to display both the modified-row view and original-row view as a single composed view. That way I can add/remvoe rows from the modified-row model and have that change effected in the composed view, all without actually affecting the original-row view/mode/underlying-data.
Assistant
Yes — what you're describing is a proxy model pattern in Qt/PyQt. Specifically, you can use:
QSortFilterProxyModel(or subclass it) to filter and transform rows from your original SQLite-backed model.QIdentityProxyModel(or subclass it) to transform data (like changing colors) without altering the underlying model.QConcatenateTablesProxyModel(fromPyQt6.QtCoreor via custom proxy) to compose multiple models into a single view — though this is not built-in in PyQt5.
However, since you want to:
- Select rows from the original model,
- Modify their appearance (e.g., change color),
- Display both original and modified rows in a single view,
- Not affect the original model,
...you can achieve this with a custom proxy model that:
- Wraps the original model,
- Keeps a list of selected row indices,
- Overrides
data()to return modified display roles (e.g., background color), - Optionally supports adding/removing rows from the modified set.
✅ Recommended Approach
1. Use a
QSortFilterProxyModelsubclassThis will act as your modified-row view. It will:
- Accept only the rows you want to show (filter),
- Override
data()to change the background color.
2. Use a custom proxy or
QConcatenateTablesProxyModel(if available)To compose the original and modified views into a single view.
If you're on PyQt6, you can use:
from PyQt6.QtCore import QConcatenateTablesProxyModelIf you're on PyQt5, you'll need to implement a custom proxy that merges two models.
🔧 Example (PyQt5 or PyQt6)
Step 1: Original model (from SQLite)
model = QSqlTableModel() model.setTable("my_table") model.select()Step 2: Proxy for modified rows
class ModifiedRowProxy(QSortFilterProxyModel): def __init__(self, parent=None): super().__init__(parent) self.modified_rows = set() # store row indices from source def setModifiedRows(self, rows): self.modified_rows = set(rows) self.invalidateFilter() def filterAcceptsRow(self, source_row, source_parent): return source_row in self.modified_rows def data(self, index, role): if role == Qt.ItemDataRole.BackgroundRole: return QColor("lightblue") # or any color return super().data(index, role)Step 3: Compose original + modified
If you're on PyQt6, use:
from PyQt6.QtCore import QConcatenateTablesProxyModel composed = QConcatenateTablesProxyModel() composed.addSourceModel(model) composed.addSourceModel(modified_proxy)If you're on PyQt5, you’ll need to write a custom proxy that merges two models — or use two views side-by-side.
✅ Summary
Task Tool Filter rows QSortFilterProxyModelChange color Override data()in proxyCompose views QConcatenateTablesProxyModel(PyQt6) or custom proxyKeep original untouched Use proxies — never modify source Let me know your PyQt version and I can tailor the code further.
- User
I like the idea of using a delegate to colour specific rows and/or using QConcatenateTablesProxyModel to form that needed single-view. One other question I have is what if I want to add new rows from another totally seperate view/model without them being added to the original-row model BUT with them being added to the composed-view. The previous question concerned affect specific rows that already existed in the original view, this question concerns the addition of not-seen before rows to that view (but not affecting the orignal-view model).
Assistant
You can keep the original model completely untouched and still let the user “add” brand-new rows to the single composed view by inserting those rows into a separate, writable model and then letting the concatenation proxy merge the two sources.
The key points are:
- The original model stays read-only (or at least you never insert into it).
- A second model (e.g.
QStandardItemModel) is used as the scratch-pad for the new rows. QConcatenateTablesProxyModel(PyQt6) or a small custom proxy (PyQt5) concatenates the two sources.- A delegate (or per-row color override in the scratch-pad model) gives the new rows their own colour.
Nothing is ever written back to the SQLite-backed model, so the original view remains unchanged.
Minimal PyQt6 example
from PyQt6.QtCore import * from PyQt6.QtGui import * from PyQt6.QtSql import * from PyQt6.QtWidgets import * app = QApplication([]) # 1. Original SQLite model (read-only for us) db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(":memory:") db.open() db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, name TEXT);") db.exec("INSERT INTO t(name) VALUES ('Alice'), ('Bob');") original = QSqlTableModel() original.setTable("t") original.select() # 2. Scratch-pad model for brand-new rows scratch = QStandardItemModel(0, 2) # same column layout scratch.setHeaderData(0, Qt.Orientation.Horizontal, "id") scratch.setHeaderData(1, Qt.Orientation.Horizontal, "name") # 3. Concatenate the two composed = QConcatenateTablesProxyModel() composed.addSourceModel(original) composed.addSourceModel(scratch) # 4. View view = QTableView() view.setModel(composed) # 5. Delegate to colour rows that come from the scratch model class ColourDelegate(QStyledItemDelegate): def initStyleOption(self, opt, idx): super().initStyleOption(opt, idx) src = idx.model().mapToSource(idx) # index in composed -> index in source if src.model() is scratch: # belongs to scratch model opt.backgroundBrush = QBrush(QColor("#ffd700")) view.setItemDelegate(ColourDelegate()) # 6. Button to add a new row (only into scratch) def add_row(): id_item = QStandardItem("999") name_item = QStandardItem("New Person") scratch.appendRow([id_item, name_item]) btn = QPushButton("Add row") btn.clicked.connect(add_row) w = QWidget() QVBoxLayout(w).addWidget(view) QVBoxLayout(w).addWidget(btn) w.show() app.exec()
PyQt5 fallback
QConcatenateTablesProxyModeldoes not exist in PyQt5.
Replace step 3 with a tiny custom proxy that simply forwards to two source models:class ConcatProxy(QAbstractProxyModel): def __init__(self, parent=None): super().__init__(parent) self._sources = [] def addSourceModel(self, src): src.rowsInserted.connect(self._source_rows_changed) src.rowsRemoved.connect(self._source_rows_changed) src.modelReset.connect(self._source_rows_changed) self._sources.append(src) self.resetInternalData() def rowCount(self, parent=QModelIndex()): return 0 if parent.isValid() else sum(m.rowCount() for m in self._sources) def columnCount(self, parent=QModelIndex()): return 0 if parent.isValid() else max(m.columnCount() for m in self._sources) def index(self, row, col, parent=QModelIndex()): if parent.isValid(): return QModelIndex() for m in self._sources: if row < m.rowCount(): return self.createIndex(row, col, m) row -= m.rowCount() return QModelIndex() def parent(self, idx): return QModelIndex() def mapFromSource(self, src_idx): if not src_idx.isValid(): return QModelIndex() row = src_idx.row() for m in self._sources: if m is src_idx.model(): return self.index(row, src_idx.column()) row += m.rowCount() return QModelIndex() def mapToSource(self, proxy_idx): if not proxy_idx.isValid(): return QModelIndex() model = proxy_idx.internalPointer() return model.index(proxy_idx.row(), proxy_idx.column()) def _source_rows_changed(self): self.beginResetModel() self.endResetModel()Then use
ConcatProxyinstead ofQConcatenateTablesProxyModel.
Result
- Original SQLite model never changes.
- New rows live only in the scratch model.
- The single view shows both sources, with new rows highlighted.
- User
Can I add new columns with a delegate? Without affecting the underlying model data? I want specific rows of a specific View of the Composite View to have different values in this new column. Can a model have multiple proxies filtering/manipulating the view? Can a view have multiple delegates manipulating the rows?
Assistant
Short answers first, then the details.
-
Can I add new columns with a delegate?
No. A delegate only paints or edits data that the model already exposes.
If the model does not contain the column, the delegate has nothing to paint. -
Can I add new columns without touching the underlying model?
Yes—use a proxy that appends extra columns (e.g. subclassQIdentityProxyModelorQAbstractProxyModel).
The proxy invents the new column(s) on-the-fly; the source model never knows they exist. -
Can a model have many proxies?
Absolutely. One source model can feed any number of proxy models, each doing its own filtering, sorting, column insertion, etc. -
Can a view have many delegates?
Only one delegate per column (or per row, if you callsetItemDelegateForRow).
If you need different behaviour for different cells you must do it inside the single delegate (e.g. switch on row/column or on a custom role).
How to add a “virtual” column only in one proxy
class ExtraColumnProxy(QIdentityProxyModel): def columnCount(self, parent=QModelIndex()): return super().columnCount(parent) + 1 # one extra column def data(self, index, role=Qt.ItemDataRole.DisplayRole): if index.column() == super().columnCount(): # virtual column if role == Qt.ItemDataRole.DisplayRole: return f"Row {index.row()} extra" return None return super().data(index, role) def headerData(self, section, orientation, role): if orientation == Qt.Orientation.Horizontal and section == super().columnCount(): if role == Qt.ItemDataRole.DisplayRole: return "Extra" return None return super().headerData(section, orientation, role)Attach this proxy only to the view that needs the extra column; the original model and any other proxies remain unchanged.
Putting it together in the composite view
SQLite model ─┬─► original-view │ ├─► ExtraColumnProxy ─┬─► ConcatenateProxy ──► single-view │ │ scratch model ─┴─► ColourDelegate ──┘ExtraColumnProxyadds the virtual column only for the rows that come from the SQLite model.ColourDelegate(or a second proxy) colours the scratch-model rows.ConcatenateProxymerges the two streams.- The original SQLite model is never modified, and the extra column never appears in any other view.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.