问题描述
下面的类是一个 QMainWindow,旨在使用 QTableView 作为中央小部件来显示我的数据库中的联系人表,但由于某种原因,我无法让我的 QsqlTableModel 对象连接到数据库,数据库文件与代码存储在同一位置,所以我不确定我做错了什么
import sys
from PyQt5.QtCore import Qt
from PyQt5.Qtsql import QsqlDatabase
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import qformlayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QAction
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QMenu
from PyQt5.Qtsql import QsqlTableModel
from PyQt5.Qtsql import QsqlQuery
from PyQt5.QtWidgets import QTableView
class Menu(QMainWindow):
model = None
con = None
cursor = None
def __init__(self):
super(Menu,self).__init__()
self.resize(415,200)
toolbar = self.addToolBar("Exit")
self.model = QsqlTableModel(self)
self.createConnection()
##Here the connection is created to the database where the contatcts table is also created
self.model.setTable("contacts") #Here i am seleecting the newly created table as the table we want to use
print(self.con.open())
self.model.setEditStrategy(QsqlTableModel.OnFieldChange)
self.model.setHeaderData(0,Qt.Horizontal,"ISO_CODE")
self.model.setHeaderData(1,"Location")
self.model.setHeaderData(2,"Date")
self.model.setHeaderData(3,"Email")
self.model.setHeaderData(4,"New_cases")
self.model.setHeaderData(3,"New_deaths")
b = self.model.select() #I tried to check if the population was succesfull cause this method returns a booelean,it always returns false and i do get a blank view so i believe it does not populate the model
print(b)
# Set up the view
self.view = QTableView()
self.view.setModel(self.model)
self.view.resizeColumnsToContents()
self.setCentralWidget(self.view)
def createConnection(self):
self.con = QsqlDatabase.addDatabase("QsqlITE")
self.con.setDatabaseName(r"C:\Users\Gabri\PycharmProjects\PyQT\recordsTest.sqlite")
if not self.con.open():
QMessageBox.critical(
None,"QTableView Example - Error!","Database Error: %s" % con.lastError().databaseText(),)
sys.exit(1)
self.cursor = QsqlQuery()
self.cursor.exec(
"""
CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,name VARCHAR(40) NOT NULL,job VARCHAR(50),email VARCHAR(40) NOT NULL
)
"""
)
print(self.con.tables())
app = QApplication(sys.argv)
win = Menu()
win.show()
sys.exit(app.exec_())
解决方法
如果您查看 QSqlTableModel 的文档:
QSqlTableModel::QSqlTableModel(QObject *parent = nullptr,QSqlDatabase
db = QSqlDatabase())
创建一个空的 QSqlTableModel 并设置
父到父和数据库连接到db。如果 db 不是
有效,将使用默认数据库连接。
默认的编辑策略是 OnRowChange。
(强调我的)
可以看出,如果不传递 QSqlDataBase(),它将使用现有连接,但在您的情况下它不存在,因此不会加载任何内容。解决办法是连接后创建QSqlTableModel:
self.createConnection()
self.model = QSqlTableModel(self)