Qt5 - QTableView with QtSql

2019-07-24 21:04发布

This is a bit of a follow on question from this one - Python referencing database connection on another script After managing to get my connection and pull data from the database, I read that using QTableView, as opposed to QTableWidget would be better for what I am trying to achieve. However, I've been struggling to get the table to populate using QTableView, and nearly every example I can find is in C++, rather than Python, and there are so many different terminologies used, it's like a minefield of undecipherable information to me. I've been trying to follow various different tutorials and examples, and I'm now getting an error message saying that QSqlQueryModel isn't defined, which I thought was pre-installed as part of Qt?

Currently, my code is as follows :

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import sys
from ViewClientsTableView import Ui_ViewClients
from OpenConn import open_conn, close_conn

class ViewClientsWindow(QtWidgets.QDialog, Ui_ViewClients):
    def __init__(self):
        super(ViewClientsWindow, self).__init__()
        self._new_window = None
        self.setupUi(self)
        self.data_load()

    def data_load(self):
        server, db = open_conn()
        model =  QSqlQueryModel()
        model.setQuery("SELECT * FROM Clients")
        model.setHeaderData(0, Qt.Horizontal, tr("ID"))
        model.setHeaderData(1, Qt.Horizontal, tr("Name"))
        view =  QTableView()
        view.setModel(model)
        view.show()
        close_conn(server, db)



if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    gui = ViewClientsWindow()
    gui.show()
    sys.exit(app.exec_())

Am I approaching things completely wrong? The purpose of this project was to try and make life a little easier, and to free up some valuable time, but currently it's doing the opposite.

Any help or advice would be greatly appreciated.... Thanks in advance

0条回答
登录 后发表回答