如何在 sqlite 数据库的 QTableView 上显示包含特定名称的所有行

How to show all rows containing a specific name on QTableView from an sqlite database

我正在使用 Pyqt 设计一个程序,用于将数据存储到 sqlite 数据库并使用 QTableView 检索它。显然,我想检索一个特定的列,如 "name" 并显示名称为 "Anderson" 的所有行。以下代码失败,因为它遗漏了很多。

database = QtSql.QSqlDatabase().addDatabase('QSQLITE')
database.setDatabaseName('database.db')
database.open()
model = QtSql.QSqlTableModel()
#model.setQuery("SELECT Name, Sale, Date FROM Individuals")
model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
model.select()
self.tableView.setModel(model)
self.tableView.setShowGrid(False)
model.setHeaderData(0, QtCore.Qt.Horizontal, "Name")
model.setHeaderData(1, QtCore.Qt.Horizontal, "Amount")
model.setHeaderData(2, QtCore.Qt.Horizontal, "Date")
self.tableView.horizontalHeader().setVisible(True)
print(model.setFilter("SELECT Name = 'Anderson' FROM Individuals"))

如果 docs 被审核:

void QSqlTableModel::setFilter(const QString &filter)

Sets the current filter to filter.

The filter is a SQL WHERE clause without the keyword WHERE (for example, name='Josephine').

If the model is already populated with data from a database, the model re-selects it with the new filter. Otherwise, the filter will be applied the next time select() is called.

你的情况:

model = QtSql.QSqlTableModel()
model.setTable("Individuals")
model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
model.select()
model.setFilter("Name='Anderson'")
self.tableView.setModel(model)