【发布时间】:2018-08-30 12:38:02
【问题描述】:
我正在尝试使用 PyQT5(在 Python3 下)构建一个 GUI,除其他外,它应该显示并允许与来自 SQLite 数据库的连接表的数据进行交互。
我认为这需要 QSqlRelationalTableModel 类。我找到了如何用另一个表中的人类可读的东西替换键的文档。
但是如何使用 PyQt5.QtSql 显示连接的 SQLite 表中的数据?( 由于 QSqlRelationalTableModel 似乎有一个 JoinMode,我认为这一定是可能的,但我无法让它工作。)
这是一个小例子(有问题的部分是 createModel() 方法):
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5 import QtSql
from PyQt5.QtWidgets import (QMainWindow, QTableView, QApplication, QAbstractItemView)
from PyQt5.QtCore import Qt
import sys
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.resize(500, 150)
self.createConnection()
self.fillTable()
self.createModel()
self.initUI()
def createConnection(self):
self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("test.db")
if not self.db.open():
print("Cannot establish a database connection")
return False
def fillTable(self):
self.db.transaction()
q = QtSql.QSqlQuery()
q.exec_("DROP TABLE IF EXISTS Manufacturers;")
q.exec_("CREATE TABLE Manufacturers (CompanyId INT PRIMARY KEY, Name TEXT, Country TEXT);")
q.exec_("INSERT INTO Manufacturers VALUES (1, 'VW', 'Germany');")
q.exec_("INSERT INTO Manufacturers VALUES (2, 'Honda' , 'Japan');")
q.exec_("DROP TABLE IF EXISTS Cars;")
q.exec_("CREATE TABLE Cars (Model TEXT, Year INT, Company INT);")
q.exec_("INSERT INTO Cars VALUES ('Civic', 2009, 2);")
q.exec_("INSERT INTO Cars VALUES ('Golf', 2013, 1);")
q.exec_("INSERT INTO Cars VALUES ('Polo', 1999, 1);")
self.db.commit()
def createModel(self):
self.model = QtSql.QSqlRelationalTableModel()
self.model.setTable("Cars")
self.model.setHeaderData(0, Qt.Horizontal, "Model")
self.model.setHeaderData(1, Qt.Horizontal, "Year")
self.model.setHeaderData(2, Qt.Horizontal, "Company")
self.model.setHeaderData(3, Qt.Horizontal, "Country") #FIXME
self.model.setRelation(2, QtSql.QSqlRelation("Manufacturers",
"CompanyId", "Name"))
self.model.select()
def initUI(self):
self.view = QTableView()
self.view.setModel(self.model)
mode = QAbstractItemView.SingleSelection
self.view.setSelectionMode(mode)
self.setCentralWidget(self.view)
def closeEvent(self, e):
if (self.db.open()):
self.db.close()
def main():
app = QApplication([])
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
运行它会显示 Cars 表,其中 CompanyId 很好地替换为 Manufacturers 表中的公司名称。但是我必须怎么做才能显示制造商表的国家列的相应条目? (即,我希望在 CompanyId 列上连接两个表,然后在 GUI 中显示连接表中的数据。)
【问题讨论】: