gpt4 book ai didi

sqlite - 使用PyQt5.QtSql从联接的SQLite表中显示数据?

转载 作者:行者123 更新时间:2023-12-03 18:43:26 32 4
gpt4 key购买 nike

我正在尝试使用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名称。但是,如何显示“制造商”表的“国家/地区”列中的相应条目呢? (即,我希望两个表都在CompanyId列上联接,然后在GUI中显示来自联接表的数据。)

最佳答案

您可以将Manufacturers表中的其他字段名添加到setRelation的第三个表达式中:

self.model.setRelation(2, QtSql.QSqlRelation("Manufacturers", "CompanyId", "Name, Country"))

关于sqlite - 使用PyQt5.QtSql从联接的SQLite表中显示数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49405544/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com