我正在尝试使用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表中的Company名称。但是,我还要做什么来显示制造商表格的Country列的相应条目? (即,我希望两个表都加入了CompanyId列,然后在GUI中显示连接表中的数据。)
答案 0 :(得分:2)
您可以将manufacturer表中的其他字段名添加到setRelation
的第三个表达式:
self.model.setRelation(2, QtSql.QSqlRelation("Manufacturers", "CompanyId", "Name, Country"))