2

I have a PyQt5 Application connecting to a MySQL database. I made two views connected to the same model. The views pull in data from the database just fine. Any change I make to any field in one is reflected in the other. But it does not update the database. I tried leaving it idle for 15 minutes and it didn't update the database.

This is my code:

from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QApplication
import sys

app = QApplication(sys.argv)

db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("usrdb")
db.setUserName("usr")
db.setPassword("passwrd")
db.open()

testModel = QSqlTableModel()
qry = QSqlQuery("select * from test", db)
testModel.setQuery(qry)
testModel.setEditStrategy(QSqlTableModel.OnFieldChange)

testView = QTableView()
testtView.setModel(testModel)
testView2 = QTableView()
testView2.setModel(testModel)

testView.show()
testView2.show()

app.exec_()

The second problem I'm having is, once I change the data in one cell, the view doesn't let me edit the data in any other cell. They are selectable, but not editable.

4

1 回答 1

2

解决了我的两个问题。pyqt 文档建议不要使用 setQuery。

您通常不应该在 QSqlTableModel 上调用它(setQuery)。相反,使用 setTable()、setSort()、setFilter() 等来设置查询。

更新代码:

from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QApplication
import sys

app = QApplication(sys.argv)

db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("usrdb")
db.setUserName("usr")
db.setPassword("passwrd")
db.open()

testModel = QSqlTableModel()
testModel.setTable("test")
testModel.setEditStrategy(QSqlTableModel.OnFieldChange)
testModel.select()

testView = QTableView()
testtView.setModel(testModel)

app.exec_()

这会在编辑完成后立即更新数据库,还可以让我在一个视图上进行多次编辑。

于 2015-05-19T16:04:34.853 回答