查询使 table 与 QTableView 和 QSqlTableModel uneditable

Query makes table with QTableView and QSqlTableModel uneditable

我需要执行查询来限制 table 中显示的行数。我选择 QTableView/QSqlTableModel 作为读写功能。不幸的是,我的查询使 table uneditable.

编辑:这不是我真正的程序。我将使用一些 table 和一个关系划分查询来确定要显示的行。我确实需要使用查询。

如何执行查询并保持读写功能?

import sys
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery

def createDb():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName("temp.db")
    if not db.open():
        print("Cannot establish a database connection.")
        return False
    query = QSqlQuery()
    query.exec_("DROP TABLE IF EXISTS customers")
    query.exec_("CREATE TABLE customers (customer_id INTEGER PRIMARY KEY NOT NULL, "
                "customer CHAR NOT NULL)")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 1')")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 2')")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 3')")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 4')")

    return True

class MainForm(QTableView):
    def __init__(self):
        super().__init__()

        self.model = QSqlTableModel(self)
        self.model.setTable("customers")

        # This query results in a non-editable table.
        self.query = QSqlQuery("SELECT customer FROM customers WHERE customer_id = 2")
        self.model.setQuery(self.query)

        self.view = QTableView(self)
        self.view.setModel(self.model)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    createDb()
    w = MainForm()
    w.show()
    sys.exit(app.exec_())

@eyllanesc 感谢您引导我使用 setFilter。

我创建了一些似乎有效的东西。我将查询结果转换为字符串。然后我使用该字符串构造一个 SQL 参数以与 setFilter 一起使用。

优雅? Pythonic?我不确定。

import sys
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery

def createDb():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName("temp.db")
    if not db.open():
        print("Cannot establish a database connection.")
        return False
    query = QSqlQuery()
    query.exec_("DROP TABLE IF EXISTS customers")
    query.exec_("CREATE TABLE customers (customer_id INTEGER PRIMARY KEY NOT NULL, "
                "customer CHAR NOT NULL)")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 1')")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 2')")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 3')")
    query.exec_("INSERT INTO customers (customer) VALUES ('Customer 4')")

    return True

class MainForm(QTableView):
    def __init__(self):
        super().__init__()

        self.model = QSqlTableModel(self)
        self.model.setTable("customers")

        self.query = QSqlQuery()
        self.query.exec("SELECT customer_id FROM customers WHERE customer_id IN (2,4)")

        # Convert query results to string.
        self.ls = list()
        while self.query.next():
            self.ls.append(self.query.value(0))
        self.ls_string = ','.join(map(str, self.ls))

        # Create setFiler argument.
        self.filter_criteria = "customer_id IN " + "(" + self.ls_string + ")"

        self.model.setFilter(self.filter_criteria)
        self.model.select()

        self.view = QTableView(self)
        self.view.setModel(self.model)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    createDb()
    w = MainForm()
    w.show()
    sys.exit(app.exec_())