i want a simple example of connecting QSqlTableModel with QTableView , connecting the QSqlTableModel to dataset file (*.db) then connecting it to QTableView ?
semi code:
from PyQt5 import QtWidgets, QtGui, QtCore, QtSql
class Main(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QVBoxLayout()
self.table = QtWidgets.QTableView()
layout.addWidget(self.table)
self.setLayout(layout)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
main = Main()
main.resize(600, 600)
main.show()
app.exec_()
The process is:
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("/path/of/database.db")
if not db.open():
sys.exit(-1)
model = QtSql.QSqlTableModel()
model.setTable("your_table")
model.select()
view = QtWidgets.QTableView()
view.setModel(model)
view.show()
sys.exit(app.exec_()
Note: In the case of sqlite if the database does not exist then it will create it so db.open()
rarely returns false.