查询使带有QTableView和QSqlTableModel的表不可编辑

时间:2019-03-25 02:11:52

标签: python sqlite pyqt pyqt5 qsqltablemodel

我需要执行查询以限制表中显示的行。我选择了QTableView / QSqlTableModel作为读写功能。不幸的是,我的查询使该表不可编辑。

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

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

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_())

1 个答案:

答案 0 :(得分:0)

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

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

优雅? 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_())