Одним из возможных решений является использование QSortFilterProxyModel
, чтобы скрыть строку:
import random
import string
from functools import partial
from PyQt5 import QtCore, QtWidgets, QtSql
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return "".join(random.sample(letters, stringLength))
def createConnection():
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(":memory:")
if not db.open():
QtSql.QMessageBox.critical(
None,
QtWidgets.qApp.tr("Cannot open database"),
QtWidgets.qApp.tr(
"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."
),
QtWidgets.QMessageBox.Cancel,
)
return False
query = QtSql.QSqlQuery()
query.exec_(
"""
CREATE TABLE "mytable" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"col1" TEXT,
"col2" TEXT,
"col3" TEXT,
"col4" TEXT,
"hide" INTEGER
);
"""
)
for _ in range(10):
query = QtSql.QSqlQuery()
query.prepare(
"""INSERT INTO mytable (col1, col2, col3, col4) VALUES(?, ?, ?, ?);"""
)
for _ in range(4):
query.addBindValue(randomString())
query.exec_()
return True
FILTER_VALUE = 1
class HideProxyModel(QtCore.QSortFilterProxyModel):
def filterAcceptsRow(self, sourceRow, sourceParent):
col = self.sourceModel().fieldIndex("hide")
ix = self.sourceModel().index(sourceRow, col, sourceParent)
return ix.data() != FILTER_VALUE
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
button = QtWidgets.QPushButton("Hide", clicked=self.onClicked)
self.m_view = QtWidgets.QTableView(
selectionBehavior=QtWidgets.QAbstractItemView.SelectRows
)
self.m_model = QtSql.QSqlTableModel()
self.m_model.setTable("mytable")
self.m_model.select()
self.m_proxy = HideProxyModel()
self.m_proxy.setSourceModel(self.m_model)
self.m_view.setModel(self.m_proxy)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(button)
lay.addWidget(self.m_view)
@QtCore.pyqtSlot()
def onClicked(self):
rows = set(
self.m_proxy.mapToSource(ix).row()
for ix in self.m_view.selectedIndexes()
)
self.m_view.clearSelection()
col = self.m_model.fieldIndex("hide")
for row in rows:
rec = self.m_model.record(row)
rec.setValue(col, FILTER_VALUE)
self.m_model.setRecord(row, rec)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = Widget()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())