使用QtSql库,我试图通过QSqlTableModel将数据加载到QTableView中。但是,当我在模型上调用select()方法时,模型中没有数据:
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtSql import *
from PyQt5.QtWidgets import QWidget, QTableView, QPushButton, QVBoxLayout
class SclDataBrowse(QWidget):
def __init__(self, parent=None):
super(SclDataBrowse, self).__init__(parent)
self.resize(336, 462)
self.setup_ui()
self.setup_db()
self.setup_model()
self.view.setModel(self.model)
if self.db.isOpen():
self.load_data()
def setup_ui(self):
self.layout = QVBoxLayout(self)
self.view = QTableView(self)
self.btn_New = QPushButton(self)
self.btn_New.setMinimumSize(QSize(70, 21))
self.btn_New.setMaximumSize(QSize(70, 21))
self.btn_New.setText('New')
self.layout.addWidget(self.view)
self.layout.addWidget(self.btn_New)
def setup_db(self):
self.db = QSqlDatabase("QMYSQL")
self.db.setHostName(myhost)
self.db.setUserName(myuser)
self.db.setPassword(mypassword)
self.db.setDatabaseName(mydb)
self.db.open()
def setup_model(self):
self.model = QSqlTableModel(self)
self.model.setTable("scldata")
self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
self.model.setHeaderData(0, Qt.Horizontal, 'ID')
self.model.setHeaderData(1, Qt.Horizontal, 'Foreign ID')
self.model.setHeaderData(2, Qt.Horizontal, 'Receipts Start')
self.model.setHeaderData(3, Qt.Horizontal, 'Receipts End')
self.model.setHeaderData(4, Qt.Horizontal, 'Billing Rate')
def load_data(self):
print('Loading Data')
self.model.select()
print(self.model.rowCount())
我这里缺少什么吗?